nlp--最大匹配分词(计算召回率)

最大匹配算法是一种常见的中文分词算法,其核心思想是从左向右取词,以词典中最长的词为优先匹配。这里我将为你展示一个简单的最大匹配分词算法的实现,并结合输入任意句子、显示分词结果以及计算分词召回率。

代码 :

复制代码
# happy coding
# -*- coding: UTF-8 -*-
'''
@project:NLP
@auth:y1441206
@file:最大匹配法分词.py
@date:2024-06-30 16:08
'''
class MaxMatchSegmenter:
    def __init__(self, dictionary):
        self.dictionary = dictionary
        self.max_length = max(len(word) for word in dictionary)

    def segment(self, text):
        result = []
        index = 0
        n = len(text)

        while index < n:
            matched = False
            for length in range(self.max_length, 0, -1):
                if index + length <= n:
                    word = text[index:index+length]
                    if word in self.dictionary:
                        result.append(word)
                        index += length
                        matched = True
                        break
            if not matched:
                result.append(text[index])
                index += 1

        return result

def calculate_recall(reference, segmented):
    total_words = len(reference)
    correctly_segmented = sum(1 for word in segmented if word in reference)
    recall = correctly_segmented / total_words if total_words > 0 else 0
    return recall

# Example usage
if __name__ == "__main__":
    # Example dictionary
    dictionary = {"北京", "天安门", "广场", "国家", "博物馆", "人民", "大会堂", "长城"}

    # Example text to segment
    text = "北京天安门广场是中国的象征,国家博物馆和人民大会堂也在附近。"

    # Initialize segmenter with dictionary
    segmenter = MaxMatchSegmenter(dictionary)

    # Segment the text
    segmented_text = segmenter.segment(text)

    # Print segmented result
    print("分词结果:", " / ".join(segmented_text))

    # Example for calculating recall
    reference_segmentation = ["北京", "天安门广场", "是", "中国", "的", "象征", ",", "国家", "博物馆", "和", "人民大会堂", "也", "在", "附近", "。"]
    recall = calculate_recall(reference_segmentation, segmented_text)
    print("分词召回率:", recall)

运行结果 :

相关推荐
视界先声8 分钟前
如何选择合适的养老服务机器人
人工智能·物联网·机器人
RPA机器人就选八爪鱼11 分钟前
RPA财务机器人:重塑财务效率,数字化转型的核心利器
大数据·数据库·人工智能·机器人·rpa
腾讯WeTest43 分钟前
Al in CrashSight ——基于AI优化异常堆栈分类模型
人工智能·分类·数据挖掘
凯子坚持 c1 小时前
openGauss向量数据库技术演进与AI应用生态全景
数据库·人工智能
嵌入式-老费1 小时前
自己动手写深度学习框架(从网络训练到部署)
人工智能·深度学习
温柔哥`2 小时前
HiProbe-VAD:通过在免微调多模态大语言模型中探测隐状态实现视频异常检测
人工智能·语言模型·音视频
强化学习与机器人控制仿真2 小时前
字节最新开源模型 DA3(Depth Anything 3)使用教程(一)从任意视角恢复视觉空间
人工智能·深度学习·神经网络·opencv·算法·目标检测·计算机视觉
机器之心2 小时前
如视发布空间大模型Argus1.0,支持全景图等多元输入,行业首创!
人工智能·openai
Elastic 中国社区官方博客2 小时前
Elasticsearch:如何创建知识库并使用 AI Assistant 来配置 slack 连接器
大数据·人工智能·elasticsearch·搜索引擎·全文检索·信息与通信
Baihai_IDP2 小时前
分享一名海外独立开发者的 AI 编程工作流
人工智能·llm·ai编程