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)

运行结果 :

相关推荐
建群新人小猿6 分钟前
陀螺匠企业助手 运行环境
java·大数据·人工智能·docker·php
renhongxia16 分钟前
基于多智能体深度强化学习的高炮反无人机算法
图像处理·人工智能·深度学习·无人机
wearegogog1239 分钟前
压缩感知和稀疏表示恢复算法中的L1同伦算法
人工智能·算法
阿水实证通12 分钟前
DoubleML+FLAML实现双重机器学习超参数的自动调优(python实现路径)
人工智能·python·机器学习·实证分析
容智信息13 分钟前
容智信息加入大模型产业联盟,Hyper Agent推动企业级智能体规模化落地
大数据·人工智能·自然语言处理·自动驾驶
core51214 分钟前
决策树 (Decision Tree):像“猜猜看”游戏一样的AI算法
人工智能·算法·决策树
catchadmin15 分钟前
使用 Laravel Workflow 作为 MCP 工具提供给 AI 客户端
人工智能·php·laravel
艾醒(AiXing-w)16 分钟前
大模型原理剖析——矩阵吸收优化:LLM推理加速的核心原理与实践
人工智能·线性代数·语言模型·矩阵
龙腾AI白云20 分钟前
知识图谱构建(2)四、知识推理五、知识表示六、图数据库七、NL2SQL#人工智能#具身智能#VLA#大模型
人工智能
元智启32 分钟前
企业AI智能体:生态融合重构生产力,中国方案领跑全球智能化转型——从单点突破到产业协同的范式革命
人工智能·重构