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)

运行结果 :

相关推荐
人工智能培训几秒前
大语言模型:从语言理解到通用智能的跃迁
linux·服务器·前端·人工智能
程序员清风几秒前
生产级智能体平台设计:任务编排、工具管理与运行监控
人工智能·python·aigc
龍德明宇3 分钟前
预言机与闭环稳定性-龍德明宇
人工智能·大语言模型llm·负主体性·ai存在论·系统论·控制论
毋小黑5 分钟前
753K 参数打赢 SwinIR:CRAFT 用「高频先验」给 Transformer 超分查漏补缺
人工智能·opencv·计算机视觉
小贺儿开发13 分钟前
Unity 结合百度AI开放平台 手写文字识别
人工智能·科技·学习·unity·云服务·文字识别·手写文字
码狂☆16 分钟前
GPT-6 Astra 上线 Codex:1.4 折接入教程
人工智能·gpt
侍伟17 分钟前
作业打卡:第三章《大语言模型基础》——本地运行 Qwen 并实现循环问答
人工智能·智能体
Omics Pro18 分钟前
上海AI Lab孙思琦×高张阳:虚拟细胞代码库智能体
数据库·人工智能·算法·机器学习·自然语言处理
goujunwe20 分钟前
企业 GEO 落地三步法:诊断、内容重构、AI 引用效果监测
大数据·人工智能·学习方法·传媒
jingli922 分钟前
恶意退款怎么办、仅退款怎么申诉:六类恶意退款识别特征+取证证据链+反制全流程(商家实操版)
人工智能·自动化·用户运营