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)

运行结果 :

相关推荐
OidEncoder22 分钟前
编码器分辨率与机械精度的关系
人工智能·算法·机器人·自动化
Championship.23.2426 分钟前
Harness工程深度解析:从理论到实践的完整指南
人工智能·harness
扬帆破浪32 分钟前
开源免费的WPS AI 软件 察元AI文档助手:链路 002:executeAssistantFromRibbon 与任务进度窗
人工智能·开源·wps
叶子Talk1 小时前
GPT-Image-2正式发布:文字渲染99%,Image Arena三项第一,AI图像生成彻底变天了
人工智能·gpt·计算机视觉·ai·openai·图像生成·gpt-image-2
不知名的老吴1 小时前
逆转训练针对大语言模型逆转训练的重要性
人工智能·深度学习·语言模型
pingao1413781 小时前
智联未来:4G温湿度传感器如何重塑数据监测新生.态
大数据·网络·人工智能
程序媛小鱼1 小时前
《All in RAG》学习笔记
人工智能
weixin_446260851 小时前
2026年IT技术趋势预测:从AIGC的狂热到Agent生态的底层重塑
人工智能·aigc
LaughingZhu1 小时前
Product Hunt 每日热榜 | 2026-04-24
人工智能·经验分享·深度学习·神经网络·产品运营
AI医影跨模态组学1 小时前
如何将CT影像组学与深度学习特征与肝细胞癌的缺氧-免疫抑制-代谢重编程恶性微环境关联,进一步解释与TACE预后及肿瘤生物学行为的机制联系
人工智能·深度学习·论文·医学·医学影像