分词算法--正向最大匹配和逆向最大匹配实现

news/2024/5/19 14:01:39 标签: 分词, tokenizer

本代码来源于《python自然语言处理实战 核心技术与算法》一书中逆向最大匹配算法实现:

假设已经有正向匹配算法源码,则可以将文档进行倒序处理,生成逆序文档,然后根据逆序词典,对逆序文档使用正向最大匹配法处理即可。同理已经存在逆向最大匹配算法,则只要将文档倒序处理,正向词典倒序变为逆序词典,则可以送入逆向西大匹配算法中进行分词处理。

 

class IMM(object):
    def __init__(self, dic_path, reversed_match = True):
        self.dictionary = set()
        self.maximun = 0
        self.reversed_match = reversed_match
        with open(dic_path, "r", encoding="utf-8-sig") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                if self.reversed_match:          #choose reverse maximum match method
                    self.dictionary.add(line)
                else:                           #choose maximum match method
                    self.dictionary.add(line[::-1])
                if len(line) > self.maximun:
                    self.maximun = len(line)
        #print(self.dictionary)
    
    def cut(self, text):
        
        if self.reversed_match:
            text = text
        else:
            text = text[::-1]
            
        index = len(text)
        result = []   #store tokenizer result
        while index > 0:
            word = []
            for size in range(self.maximun, 0, -1):
                if index < size:
                    continue
                piece = text[(index - size): index]
                if piece in self.dictionary:
                    word = piece
                    if self.reversed_match:
                        result.append(word)
                    else:
                        result.append(word[::-1])
                    index -= size
                    break
            if not word:
                index -= 1
        if self.reversed_match:
            return result[::-1]
            
        else:
            return  result
path = r"E:\\学习相关资料\\python自然语言处理实战核心技术与算法--代码\\第三章"
doc = r"imm_dic.txt"
text = "南京市长江大桥"
doc_in_path = path + "\\" + doc
tokenizer = IMM(doc_in_path)
print(tokenizer.cut(text))

tokenizer = IMM(doc_in_path, reversed_match=False)
print(tokenizer.cut(text))

 其中,imm_dic.txt内容为:

南京市
南京市长
长江大桥
人民解放军
大桥
江大桥

 

这里,将字符串反转的实现方式是:

x = "hello world"
z = x[::-1]
print(z)

将字符串逐字符反转

 

在打开文件处,

encoding="utf-8-sig"
encoding="utf-8"

主要是发现

dic = []
with open(doc_in_path, "r", encoding="utf-8-sig") as f:
    for line in f:
        line = line.strip()
        if line:
            dic.append(line)
print(dic)


['南京市', '南京市长', '长江大桥', '人民解放军', '大桥', '江大桥']
dic = []
with open(doc_in_path, "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if line:
            dic.append(line)
print(dic)

['\ufeff南京市', '南京市长', '长江大桥', '人民解放军', '大桥', '江大桥']

"\ufeff"的存在,限制我只能使用“utf-8-sig”

 

 


http://www.niftyadmin.cn/n/632146.html

相关文章

给定一个数,求平方根, Python实现,最小二分法和牛顿法

import datetime, time import math eps 0.001 def SqrtByBisection(n): #二分法逼近global epsif n < 0:return nlow 0 * 1.0up n * 1.0mid (low up)/2last 0while abs(mid - last) > eps:if mid * mid > n:up midelse:low midlast midmid (low up)/2ret…

java时间差得到年月日

&#xfeff;&#xfeff;package action; import java.util.Calendar; import java.util.Date; import util.Util; /**** Test01 * 创建人&#xff1a;Ming* 创建时间&#xff1a;2016-4-28日 -上午09:44:00* version 1.0.0 **/ public class Test01 {/*** 时间差得到 年-月-日…

jieba下TextRank实现

TextRank实现步骤如下&#xff1a; #这一段是抄了别人的 &#xff08;1&#xff09;把给定的文本按照完整的句子进行分割&#xff1b; &#xff08;2&#xff09;对每个句子进行分词和词性标注&#xff0c;过滤停用词&#xff0c;只保留特定词性&#xff1b; &#xff0…

JAVA定时器启动日期

/** * 每个月执行一次 * 参数说明&#xff1a;* day:一个月中的哪一天&#xff0c;默认为当前天* hour:几点钟* minute:分钟* second:秒 默认为00:00:00 */public static Date getTargetDate(int day, int hour, int minute, int second) {Date date new Date();Calendar …

对jieba分词的 分词模型进行抽取,简单实现

因为水平一般&#xff0c;所以将jieba库中分词模块的代码进行简化&#xff0c;这里全部使用函数实现 import jieba from jieba.finalseg.prob_emit import P as emit_p from jieba.finalseg.prob_start import P as start_p from jieba.finalseg.prob_trans import P as trans…

JS 点击标题进行排序

<!DOCTYPE html> <html><head> <title>JS点击标题排序</title> <meta http-equiv"keywords" content"keyword1,keyword2,keyword3" /> <meta http-equiv"description" content"this is my page&quo…

Python anaconda nltk_data安装步骤

&#xff08;1&#xff09;到GitHub查找源&#xff0c;https://github.com/nltk/nltk_data &#xff08;2&#xff09;如图所示&#xff0c;将packets下载下来 &#xff08;3&#xff09;打开jupyter&#xff0c;输入如下两行代码 import nltk nltk.data.find(".")…

go依赖注入_Go 每日一库之 Uber 的依赖注入库 dig

简介今天我们来介绍 Go 语言的一个依赖注入(DI)库——dig。dig 是 uber 开源的库。Java 依赖注入的库有很多&#xff0c;相信即使不是做 Java 开发的童鞋也听过大名鼎鼎的 Spring。相比庞大的 Spring&#xff0c;dig 很小巧&#xff0c;实现和使用都比较简洁。快速使用第三方库…