1. 程式人生 > >正向最大匹配演算法實現之python實現

正向最大匹配演算法實現之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