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)

运行结果 :

相关推荐
这张生成的图像能检测吗几秒前
(论文速读)TDANN:用于轴承故障诊断的三域对抗神经网络
人工智能·深度学习·神经网络·故障诊断
Agent产品评测局6 分钟前
企业自动化项目,如何做好内部推广与员工培训?——企业级智能体落地与人才赋能实测指南
运维·人工智能·ai·chatgpt·自动化
大数据在线9 分钟前
当AI重构攻防,华为星河AI网络安全如何重塑安全底座
人工智能·安全·智能体·ai安全·华为星河ai网络
ryrhhhh19 分钟前
低延迟高精准:陌讯AIGC检测如何破解AI内容审核效率难题
人工智能·aigc
企服AI产品测评局21 分钟前
AI突围:不下场,就出局!实测「实在Agent」,手搓数字员工的降维打击
人工智能·ai
AI专业测评25 分钟前
2026网文提速:实测8款顶级AI码字神器,网址全公开,建议收藏!
人工智能
俊哥V30 分钟前
每日 AI 研究简报 · 2026-03-28
人工智能·ai
文艺倾年31 分钟前
【2026持续更新】OpenClaw + OpenCode/Claude + CoWork + 源码讲解百万字教程
人工智能·python
hguisu41 分钟前
AI大模型-2:智能体(Agent)和demo演示实践
人工智能
墨染天姬43 分钟前
【AI】英伟达 AVO 自动生成GPU算子
人工智能