正向最大匹配算法实现之python实现

1.python 版本:python 3.6.4
2.思路:
s1.导入分词词典,存储为字典形式dic,导入停用词词典stop_words,存储为字典形式,需要分词的文本文件cutTest.txt,存储为字符串chars
s2.遍历分词词典,找出最长的词,长度为max_chars
s3.创建空列表words来存储分词结果
s4.初始化字符串chars分词起点n=0
s5.判断分词点n是否在字符串chars内,即n < len(chars)成立,则进入下一步骤,否则进入s9
s6.根据分词长度i(初始值为max_chars)截取相应的需分词文本chars的字符串s
s7.判断s是否存在于分词词典中,若存在,则分两种情况讨论,一是s是停用词,分词起点n后移i位,转到步骤5;二是s不是停用词,那么直接添加到分词结果words中,分词起点n后移i位,转到步骤5;若不存在,则分两种情况讨论,一是s是停用词,那么添加到分词结果中,分词起点后移i位,转到步骤5;二是s不是停用词,分词长度i > 1时,分词长度i减少1,转到步骤6, 若是此时s是单字,则转入步骤8;
s8.将s添加到分词结果words中,分词起点n后移1位,转到步骤5
s9.将需分词文本chars的分词结果words输出到文本文件result.txt中
3.代码实现

import codecs

#获得分词字典,存储为字典形式
f1 = codecs.open('./corpus/WordList.txt', 'r', encoding='utf8')
dic = {}
while 1:
    line = f1.readline()
    if len(line) == 0:
        break
    term = line.strip() #去除字典两侧的换行符,避免最大分词长度出错
    dic[term] = 1
f1.close()

#获得需要分词的文本,为字符串形式
f2 = codecs.open('./corpus/cutTest.txt', 'r', encoding='utf8')
chars = f2.read().strip()
f2.close()

#获得停用词典,存储为字典形式
f3 = codecs.open('stop_words.txt', 'r', encoding='utf8')
stoplist = {}
while 1:
    line = f3.readline()
    if len(line) == 0:
        break
    term = line.strip()
    stoplist[term] = 1
f3.close()

#正向匹配最大分词算法
#遍历分词词典,获得最大分词长度
max_chars = 0
for key in dic:
    if len(key) > max_chars:
        max_chars = len(key)

#定义一个空列表来存储分词结果
words = []
n = 0
while n < len(chars):
    matched = 0
    #range([start,] stop[, step]),根据start与stop指定的范围以及step设定的步长 step=-1表示去掉最后一位
    for i in range(max_chars, 0, -1): #i等于max_chars到1
        s = chars[n : n + i] #截取文本字符串n到n+1位
        #判断所截取字符串是否在分词词典和停用词词典内
        if s in dic:
            if s in stoplist: #判断是否为停用词
                words.append(s)
                matched = 1
                n = n + i
                break
            else:
                words.append(s)
                matched = 1
                n = n + i
                break
        if s in stoplist:
            words.append(s)
            matched = 1
            n = n + i
            break
    if not matched: #等于 if matched == 0
        words.append(chars[n])
        n = n + 1
#分词结果写入文件
f3 = open('MMResult.txt','w', encoding='utf8')
f3.write('/'.join('%s' %id for id in words))
f3.close()

4.运行结果
(1)cutTest.txt文本内容:
中文分词指的是将一个汉字序列切分成一个个单独的词。
(2)MMResult内容如图:
这里写图片描述
5.参考资料
1.https://blog.csdn.net/lalalawxt/article/details/75458791

猜你喜欢

转载自blog.csdn.net/Cuixinyang19_/article/details/82251553