正向最大匹配
def forward_match(text,item_dict):
"""
:param text: 分词文本
:param item_dict: 指导分词
"""
resList = [] # 存放结果
LongWord = max([len(word) for word in item_dict]) # 计算指导词语中最长长度
# 读取测试文本最大值开始递减 匹配
while text:
word = text[:LongWord] # 进行缩减最大值文本
# 当word不在item中进行
# 1:匹配到直接存入结果
# 2:没有匹配到 就开始缩减文本匹配
while word not in item_dict:
if len(word) == 1: # 匹配边缘单词 直接添加到结果中
break
word = word[:-1]
resList.append(word) # 添加到结果中
# 在最大文本中删除掉这个存入的值
text = text[len(word):]
return resList
最大逆向匹配
def backward_match(text,item_dict):
"""
:param text: 分词文本
:param item_dict: 指导分词
"""
resList = [] # 存放结果
LongWord = max([len(word) for word in item_dict]) # 计算指导词语中最长长度
# 读取测试文本最大值开始递减 匹配
while text:
word = text[-LongWord:] # 进行缩减最大值文本
# 当word不在item中进行
# 1:匹配到直接存入结果
# 2:没有匹配到 就开始缩减文本匹配
while word not in item_dict:
if len(word) == 1: # 匹配边缘单词 直接添加到结果中
break
word = word[1:]
resList.append(word) # 添加到结果中
# 在最大文本中删除掉这个存入的值
text = text[:-len(word)]
return resList
最大双向匹配
def bidirectional_match(text, item_dict):
f = forward_match(text, item_dict)
b = backward_match(text, item_dict)
if len(f) < len(b):
return f
elif len(f) > len(b):
return b
else:
# 如果正向和逆向匹配结果长度不同,选择词数目较少的
if sum([len(word) == 1 for word in f]) < sum([len(word) == 1 for word in b]):
return f
else:
return b # 都相等时逆向匹配优先级更高