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)

运行结果 :

相关推荐
lovingsoft16 分钟前
AI 开发的软件质量如何保证?一套可落地的 LLM 应用质量工程体系(QA 视角)
人工智能
小易测试笔记27 分钟前
如何选择适合的半导体静电放电测试设备,易捷测试 Hanwa中国区代理提供哪些支持?
人工智能
益莱储中国28 分钟前
益莱储任命 Vincent Kwa为亚太区副总裁兼总经理
大数据·人工智能
鬼手点金30 分钟前
上下文:Agent 的眼睛
java·前端·人工智能·git·深度学习
具身AGI34 分钟前
一块远程显卡服务一队机器人,瓶颈不在模型
人工智能·机器人
hzxxxz34 分钟前
AI任务分流链路:从3层可验证路由到判断力留痕
人工智能
我有酒两杯36 分钟前
从一条样本看懂 Kev:数据、模型、训练与推理
人工智能·深度学习·机器学习·lora·大语言模型
EterNity_TiMe_38 分钟前
Docker服务越装越多记不住端口?我用Fenrus把NAS里的常用入口整理成一个导航页
运维·人工智能·docker·ai·容器·cpolar
晨间晓1 小时前
图片里的关键点怎么找?用华为云码道开发 OpenCV FAST 特征点检测工具
人工智能·opencv·华为云
科创致远1 小时前
科创致远 ESD 静电监控全景落地指南
人工智能·信息可视化·制造·精益工程