自然语言处理--分词正向最大匹配,逆向最大匹配和双向最大匹配

逆向最大匹配

词典word.txt

南京
南京市
长江
长江大桥
大桥
南京市长
市长
北京
北京市长
烤鸭
南京烤鸭

 

 

逆向最大

class IMM(object):
    def __init__(self,dic_path):
        #集合
        self.dictionary = set()
        self.maximum = 0
        #读取词典
        with open(dic_path,'r',encoding='utf8') as f:
            for line in f:
                line = line.strip()
                if line:
                    self.dictionary.add(line)
            self.maximum = len(self.dictionary)

    def cut(self,text):
        #用于存放切分出来的词
        result = []
        index = len(text)
        #记录没有在词典中的词,可以用于发现新词
        no_word = ''
        while index > 0:
            word = None
            #从前往后匹配,以此实现最大匹配
            for first in range(index):
                if text[first:index] in self.dictionary:
                    word = text[first:index]
                    #如果之前存放了字典里面没有出现过的词
                    if no_word != '':
                        result.append(no_word[::-1])
                        no_word = ''
                    result.append(text[first:index])
                    index = first
                    break
            if word == None:
                index = index -1
                no_word += text[index]
        return result[::-1]

if __name__ == '__main__':
    text = '北京市长喜欢南京烤鸭和南京市长江大桥'
    tokenizer = IMM('word.txt')
    print(tokenizer.cut(text))

 

运行结果:

正向最大匹配:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值