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)

运行结果 :

相关推荐
breeze jiang6 分钟前
Vibe Coding 越写越乱?用 Harness Engineering 给 AI 开发加上流程
人工智能
霍格沃兹测试开发学社测试人社区10 分钟前
2026被称“最难秋招季”?软件测试人,你的机会藏在这3个变化里
人工智能
天天爱吃肉821811 分钟前
AI Agent时代你的经验值多少钱?
人工智能·python·功能测试·学习·汽车
GAOJ_K21 分钟前
老旧产线弧形导轨换新:同规格替换避坑选型思路
人工智能·算法·机器学习·制造·导轨偏磨
zzzzzz31024 分钟前
当老板说「数据库里加个字段就行了」时,我在想什么——一个后端开发的奇葩需求大赏
数据库·人工智能·产品经理
Figo_Cheung26 分钟前
以“道”为鉴:当代人如何践行健康的“养”与“拼”之辨——以道德经智慧解构现代人精神疲惫症候群
人工智能
kkai人工智能1 小时前
聚合90家免费API、独创Token压缩、免20美元月费:免费Claude Code
人工智能
fanstuck6 小时前
1M 上下文能怎么用?我用 Seed Evolving 做了一个招标文件版本差异审查器
服务器·人工智能·数据分析·开源·aigc
墨舟的AI笔记8 小时前
React 组件库的 Tree Shaking:按需加载与副作用的工程化治理
人工智能
WoooChi9 小时前
DailyTech-20260724
人工智能·科技·业界资讯