最大匹配算法進行分詞 前向 后向 python實現


# 先定義個詞典
word_dict = ['我們', '經常', '有','有意見','意見','分歧']
# 滑動窗口的大小
max_len = 5 
# 用戶的輸入
user_input = '我們經常有意見分歧'
len(user_input)
結果:
9

 前向最大匹配算法的實現

# 前向最大匹配算法
result = []
i = 0 
while i < len(user_input): 
    matched = False 
    pos = i + max_len if i + max_len < len(user_input) else len(user_input)
    while user_input[i:pos] not in word_dict and i < pos:
        print(user_input[i:pos]) 
        pos -= 1 
    if i < pos: 
        matched = True
        result.append(user_input[i:pos])
    i = pos if matched == True else i + max_len         
print(result)

輸出結果:

我們經常有
我們經常
我們經
經常有意見
經常有意
經常有
有意見分歧
有意見分
['我們', '經常', '有意見', '分歧']


后向最大匹配算法的實現
# 后向最大匹配算法 
result = []
i = len(user_input) 
while i > 0: 
    matched = False 
    pos = i - max_len if i - max_len > 0 else 0 
    while user_input[pos:i] not in word_dict and i > pos:
        print(user_input[pos:i]) 
        pos += 1      
    if i > pos:
        matched = True 
        result.insert(0, user_input[pos:i])
    i = pos if matched == True else i - max_len
print(result) 

輸出結果:

有意見分歧
意見分歧
見分歧
經常有意見
常有意見
我們經常
們經常
['我們', '經常', '有意見', '分歧']


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM