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)

运行结果 :

相关推荐
kaixin_啊啊13 分钟前
【零基础学AI】第 34 章课后练习与答案
人工智能
always20221 小时前
AI运行时 · 04 - Kata Containers 整体架构
人工智能·架构
星恒随风1 小时前
从0实现C++ AI大模型接入SDK(七):Ollama本地模型部署、NDJSON流式响应与LLMManager模型管理
linux·开发语言·c++·人工智能·笔记
zhinengws1 小时前
沃思智能智能路灯监控终端:从项目落地到智慧城市生态的深度观察
网络·人工智能·智慧城市·智能路灯监控终端
真上帝的左手2 小时前
4. 关系型数据库-MySQL-原生集成 AI能力
数据库·人工智能·mysql·ai
深频率2 小时前
补丁还在排队,AI先替服务器挡了一刀
服务器·人工智能·jenkins
谙弆悕博士2 小时前
生物启发式集群(Swarm)工程实现:五条规则、一群蚂蚁和四十个粒子
人工智能·gpt·游戏引擎·cocos2d·蚁群算法·多智能体·boids
Summer-Bright3 小时前
深度 | 微调接棒开源:权重免费后,后训练成了云厂商的新收费单元
人工智能·开源·llm·微调·强化训练
大模型真好玩3 小时前
为什么国产大模型进步放缓了?
人工智能·agent·deepseek
前进的李工3 小时前
Agent 学习笔记 26:多 Agent 协作的设计与选型
人工智能·消息传递·成本优化·分布式系统·多agent·上下文管理·多轮agent