考虑一下,我有一个清单。list1=['car', 'bike', 'van', 'class']
,而我正在解析一个文本文件。该文本文件可以包含不在此列表中并且不是此列表中单词的拼写错误的其他任意单词。
如果文件中有“ ca”,则我的算法会将其替换为“ car”
如果文件包含“ bke”,则将其替换为“ bike”
如果文件包含“ clss”,则将其替换为“ class”
我的算法基本上是纠错算法。如何用列表中的单词替换相关的拼写错误的单词?
任何问题的答案将不胜感激!
使用levenshtein算法,您可以执行以下操作:
tgt_list='ca bke clss'.split()
for word in ['car','bike','van','class']:
wdist_exp=((w, levenshtein(w, word)) for w in tgt_list)
closest, dist=min(wdist_exp, key=lambda t: t[1])
print '{}=>{} ld={}'.format(closest,word,dist)
印刷品:
ca=>car ld=1
bke=>bike ld=1
ca=>van ld=2
clss=>class ld=1
regex模块也可以:
import regex
template='{}=>{} with {} substitutions, {} insertions, {} deletions'
tgt='ca bke clss'
for word in ['car','bike','van','class']:
pat=r'((?:\b{}\b){{e<=2}})'.format(word)
m=regex.search(pat, tgt, regex.BESTMATCH)
if m:
print template.format(m.group(1),word,*m.fuzzy_counts)
印刷品:
ca =>car with 1 substitutions, 0 insertions, 0 deletions
bke=>bike with 0 substitutions, 0 insertions, 1 deletions
ca =>van with 2 substitutions, 0 insertions, 0 deletions
clss=>class with 0 substitutions, 0 insertions, 1 deletions
您可能想使用此处使用的类似方法研究Python的difflib模块。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句