# 先定義個詞典 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)
輸出結果:
有意見分歧 意見分歧 見分歧 經常有意見 常有意見 我們經常 們經常 ['我們', '經常', '有意見', '分歧']