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)

运行结果 :

相关推荐
GISer_Jing2 分钟前
Agent多代理架构:子代理核心机制解密
开发语言·人工智能·架构·aigc
roamingcode3 分钟前
前端 AI Agent 多智能体协作架构:从对抗式排查到工作流解耦
前端·人工智能·架构·agent·team
songcream14 分钟前
TensorFlow的一些基本概念
人工智能·python·tensorflow
智慧医院运行管理解决方案专家17 分钟前
中科医信杜鹏:「数据驱动,孪生赋能」,数据资产是医院智慧管理的核心要素之一
大数据·人工智能·数字孪生·智慧医工管理
smileNicky20 分钟前
Spring AI系列之Tool Calling实战指南
人工智能·spring boot·spring
珠海西格电力25 分钟前
鄂尔多斯零碳产业园管理系统的核心功能解析
大数据·运维·人工智能·物联网·能源
爱学习的小囧28 分钟前
VCF 9.0+Harbor 搭建私有 AI 模型仓库(PAIS)超详细教程
服务器·人工智能·虚拟化·esxi8.0
YoanAILab33 分钟前
从 CoT、RAG 到 Dify、Deep Research:一篇讲清 AI 问答系统的两条进化路线
人工智能·cot·dify·rag·deepresearch
GEO索引未来41 分钟前
一文说清2026年GPT 卖货两种方式
人工智能·gpt·ai·chatgpt