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)

运行结果 :

相关推荐
朝阳眯眼几秒前
Android 集成OpenCV
android·人工智能·opencv
Faris_yzf10 分钟前
人工智能在反无人机中的应用介绍
人工智能·科技·算法·安全·无人机
三花AI32 分钟前
小红书 达芬奇:生活问答 AI 机器人
人工智能·机器人·生活
西西弗Sisyphus38 分钟前
在卷积神经网络(CNN)中为什么可以使用多个较小的卷积核替代一个较大的卷积核,以达到相同的感受野
人工智能·神经网络·cnn
游戏智眼44 分钟前
自从棋牌游戏有了AI助阵,赢“麻”了!看这篇就够了
大数据·人工智能·游戏·ai·游戏引擎·aigc·游戏策划
人工智能培训咨询叶梓1 小时前
Lumière:开创性的视频生成模型及其应用
人工智能·深度学习·机器学习·语言模型·自然语言处理·音视频·多模态
风暴统计1 小时前
风暴统计案例复现 | 先单后多的影响因素分析
人工智能·数据挖掘·回归
交换喜悲1 小时前
深度学习之半监督学习:一文梳理目标检测中的半监督学习策略
论文阅读·人工智能·python·学习·目标检测·计算机视觉·目标跟踪
汀、人工智能1 小时前
煤矿安全大模型:微调internlm2模型实现针对煤矿事故和煤矿安全知识的智能问答
人工智能·ai大模型
爱看书的小沐1 小时前
【小沐学AI】Python实现语音识别(faster-whisper-webui)
人工智能·python·ai·nlp·whisper·语音识别·fast-whisper