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)

运行结果 :

相关推荐
qq_411262422 分钟前
四博 AI 机械臂台灯智能音箱方案:让台灯具备视觉、语音、动作和学习陪伴能力
人工智能·语音识别
AI+程序员在路上14 分钟前
VS Code 完全使用指南:下载、安装、核心功能与 内置AI 编程助手实战
开发语言·人工智能·windows·开源
coderyi23 分钟前
Agent协作简析
人工智能
霍小毛1 小时前
破局工业数据孤岛!数字孪生+AI智慧设备资产管理平台,重构智能运维新范式
人工智能·重构
向量引擎1 小时前
向量引擎的新时代:从OpenClaw、Hermes到GPT Image 2与龙虾(Lobster)模型的深度对比与应用
人工智能·gpt·aigc·api·ai编程·key·api调用
2501_941149111 小时前
智能家居的无声守护者:物联网系统自动化测试落地经验
人工智能·语音识别
ComputerInBook1 小时前
数字图像处理(4版)——第 7 章——小波及其它图像变换(上)(Rafael C.Gonzalez&Richard E. Woods)
人工智能·机器学习·数字图像处理·图像变换
冬奇Lab2 小时前
烧了数千美金 Token,我用 AI Agent 打通了企业级 Bug 修复全流程
人工智能·debug
冬奇Lab2 小时前
一天一个开源项目(第85篇):TypeScript 巫师把自己的 Claude 配置推到了 GitHub,一夜全球第一
人工智能·开源·claude
爱艺江河2 小时前
智慧合规的HarmonyOS原生实践:与OpenClaw适配的项目方案浅析
人工智能·华为·harmonyos