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)

运行结果 :

相关推荐
ai生成式引擎优化技术4 分钟前
全球唯一四元结构底层架构问世:TSPR-WEB-LLM-HIC v2.0 终结大模型投毒与幻觉的终极技术范式
人工智能
听你说3213 分钟前
伊萨推出 ROBBI 360 协作机器人焊接工作站 简化自动化焊接部署流程
人工智能·机器人·自动化
weixin_4080996714 分钟前
【实战对比】在线 OCR 识别 vs OCR API 接口:从个人工具到系统集成该怎么选?
图像处理·人工智能·后端·ocr·api·图片文字识别·文字识别ocr
罗西的思考28 分钟前
【OpenClaw】通过Nanobot源码学习架构---(2)外层控制逻辑
人工智能·机器学习
火山引擎开发者社区37 分钟前
明天武汉!用好“龙虾”的关键要素全在这儿
人工智能
梦想很大很大39 分钟前
从 0 到 1 实现 AI Agent(02):设计可扩展的 Tool 调用系统
人工智能·llm·agent
木斯佳41 分钟前
HarmonyOS 6实战:AI时代的“信任危机“,如何处理应用的请求拦截与安全防护
人工智能·安全·harmonyos
jkyy201442 分钟前
食物识别与卡路里估算技术:以视觉技术重构膳食健康管理新范式
人工智能·语言模型·自动化·健康医疗
冬奇Lab1 小时前
一天一个开源项目(第61篇):knowledge_graph - 把任意文本转成知识图谱
人工智能·llm
wdf80881 小时前
算力随行:UltraLAB便携工作站如何将多卡深度学习带入户外与现场
人工智能·深度学习·大模型推理·无人机影像