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)

运行结果 :

相关推荐
opentrending16 分钟前
Github 热点项目 awesome-mcp-servers MCP 服务器合集,3分钟实现AI模型自由操控万物!
服务器·人工智能·github
lisw051 小时前
DeepSeek原生稀疏注意力(Native Sparse Attention, NSA)算法介绍
人工智能·深度学习·算法
whaosoft-1431 小时前
51c深度学习~合集4
人工智能
逢生博客1 小时前
阿里 FunASR 开源中文语音识别大模型应用示例(准确率比faster-whisper高)
人工智能·python·语音识别·funasr
哲讯智能科技2 小时前
智慧能源新篇章:SAP如何赋能光伏行业数字化转型
大数据·人工智能
云卓SKYDROID2 小时前
无人机DSP处理器工作要点!
人工智能·无人机·科普·云卓科技
gang_unerry2 小时前
量子退火与机器学习(2):少量实验即可找到新材料,黑盒优化➕量子退火
人工智能·机器学习·量子计算·量子退火
訾博ZiBo2 小时前
AI日报 - 2025年4月2日
人工智能
说私域2 小时前
消费品行业创新创业中品类创新与数字化工具的融合:以开源 AI 智能客服、AI 智能名片及 S2B2C 商城小程序为例
人工智能·小程序·开源
说私域2 小时前
开源AI大模型赋能的S2B2C商业生态重构研究——基于智能名片系统的体验认知与KOC背书机制
人工智能·小程序·重构·开源