今天学习了一种自然语言匹配中的中文分词方法,逆向最大匹配。
"""
author: 15025
time: 2021/8/4 7:51
software: PyCharm
Description:
逆向最大匹配: Reverse Maximum Match Method(RMM)
"""
class RMM:
def __init__(self, dict_path):
self.dictionary = set()
self.maximum = 0
with open(dict_path, 'r', encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
self.dictionary.add(line)
if len(line) > self.maximum:
self.maximum = len(line)
def cut(self, text):
result = []
index = len(text)
while index > 0:
word = None
for size in range(self.maximum, 0, -1):
if index - size < 0:
continue
print(piece)
if piece in self.dictionary:
word = piece
result.append(word)
index -= size
break
if word is None:
index -= 1
return result[::-1]
if __name__ == '__main__':
text_ = "西安市大雁塔"
file_path = r"C:/Users/15025/Desktop/NLP/IMM_Dict.txt"
NLP = RMM(file_path)
print(NLP.cut(text_))
"""
['西安市', '大雁塔']
"""
其中对应的IMM_Dict 字典文件内容如下图所示。 代码注释已经十分清晰了,这里不做过多的解释了,如果在阅读时遇到问题,可以评论区留言给我。
码字不易,如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~
|