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)

运行结果 :

相关推荐
沸点小助手5 分钟前
「新晋AI顶流PK:GPT-5.5 vs DeepSeek V4&掘友吐槽小会」沸点获奖名单公示|本周互动话题上新🎊
前端·人工智能
nikolay5 分钟前
AI重塑企业信息安全:攻防升级与信任重构
网络·人工智能·网络安全
天辛大师17 分钟前
天辛大师谈人工智能时代,如何用AI研究历代放生劝善忏悔文
大数据·人工智能·随机森林·启发式算法
lazy_ma25 分钟前
(二)大模型实操- Skill 入门:从原理到第一个可调用工具
人工智能
ComputerInBook27 分钟前
数字图像处理(4版)——第 9 章——形态学图像处理(Rafael C.Gonzalez&Richard E. Woods)
图像处理·人工智能·计算机视觉·形态学·数学形态学
eastyuxiao40 分钟前
如何用思维导图拆解项目范围
大数据·人工智能·流程图
机器之心1 小时前
DeepSeek版Claude Code登顶热榜:8700星,鲸鱼哥火了
人工智能·openai
易标AI1 小时前
标书智能体(五)——如何让弱模型也能稳定输出复杂json
人工智能·python·提示词·智能体·招投标
:mnong1 小时前
模具非标件报价-精密算盘智能体SOP
人工智能·cad
技术人生黄勇1 小时前
GitNexus 把代码库变成知识图谱|审核 AI 产出更清晰,改 Bug 更精准
人工智能·bug