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)

运行结果 :

相关推荐
Agent手记13 分钟前
成本数据多系统自动采集与分析实操指南:基于2026大模型Agent的超自动化实践
运维·人工智能·microsoft·ai·自动化
陈天伟教授18 分钟前
图解人工智能(34)深度学习面临的挑战
人工智能·深度学习·神经网络·cnn
拉卡拉开放平台20 分钟前
支付系统在文旅场景的进阶之路:聚合收单、分账与自动化对账
大数据·人工智能·自动化
jovi_AI电报36 分钟前
ChatGPT 对话太多,之前聊的好东西找不到了
人工智能·chatgpt
老鱼说AI37 分钟前
统计学习方法第一章讲解:统计与监督学习概率
人工智能·学习·学习方法
山川绿水39 分钟前
Bugku——原神祈愿
人工智能·网络安全·claude
gjhave41 分钟前
jetson上trtexec模型转换
人工智能·机器学习
互联网推荐官42 分钟前
2026上海GEO优化服务商综合实力深度评测
大数据·人工智能·技术分享·geo·上海
Dfreedom.1 小时前
算子融合:从硬件本质到性能飞跃的深度学习优化艺术
人工智能·深度学习·gpu·gpu加速·模型加速·算子融合·模型计算
QYR_111 小时前
4.3% 年复合增速:2026全球救生衣灯市场格局与海事合规发展报告
大数据·人工智能