逆向最大匹配演算法之python實現
阿新 • • 發佈:2018-11-21
1.執行環境
python 3.6.4
2.思路
大致思路與正向相同,可參考我的上一篇部落格。
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/zoo.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 = len(chars) #待分詞文字的長度
while n > 0:
matched = 0
#range([start,] stop[, step]),根據start與stop指定的範圍以及step設定的步長 step=-1表示去掉最後一位
for i in range(max_chars, 0, -1): #i等於max_chars到1
if n - i < 0: #若待分詞文字長度小於最大字典詞長,則終止迴圈
continue
s = chars[n - i : n] #擷取文字字串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 - 1: n])
n = n - 1
words.reverse()
#分詞結果寫入檔案
f3 = open('RMMResult.txt','w', encoding='utf8')
f3.write('/'.join('%s' %id for id in words))
f3.close()
4.執行結果
待分詞文字:zoo.txt
粉刺結果:RMMResult.txt
5.參考資料
(1)Python自然語言處理實戰 核心技術與演算法