ebe*_*tos 6 python spell-checking
我有一个城市名称列表,其中一些拼写错误:
['bercelona', 'emstrdam', 'Praga']
Run Code Online (Sandbox Code Playgroud)
并列出了所有可能的城市名称拼写清楚:
['New York', 'Amsterdam', 'Barcelona', 'Berlin', 'Prague']
Run Code Online (Sandbox Code Playgroud)
我正在寻找能够找到第一个和第二个列表名称之间最接近匹配的算法,并返回带有拼写清晰名称的第一个列表.所以它应该返回以下列表:
['Barcelona', 'Amsterdam', 'Prague']
Run Code Online (Sandbox Code Playgroud)
您可以使用内置的Ratcliff和Obershelp算法:
def is_similar(first, second, ratio):
return difflib.SequenceMatcher(None, first, second).ratio() > ratio
first = ['bercelona', 'emstrdam', 'Praga']
second = ['New York', 'Amsterdam', 'Barcelona', 'Berlin', 'Prague']
result = [s for f in first for s in second if is_similar(f,s, 0.7)]
print result
['Barcelona', 'Amsterdam', 'Prague']
Run Code Online (Sandbox Code Playgroud)
其中0.7是相似系数.它可能会对您的案例进行一些测试并设置此值.它显示了两个字符串的相似程度(1 - 它是相同的字符串,0 - 非常不同的字符串)
这可能是一个名为Fuzzywuzzy的优秀软件包的一个很好的用例。
from fuzzywuzzy import fuzz
import numpy as np
bad = ['bercelona', 'emstrdam', 'Praga']
good = ['New York', 'Amsterdam', 'Barcelona', 'Berlin', 'Prague']
# you can even set custom threshold and only return matches if above certain
# matching threshold
def correctspell(word, spellcorrect, thresh = 70):
mtchs = map(lambda x: fuzz.ratio(x, word) if fuzz.ratio(x, word) > thresh else None, spellcorrect)
max = np.max(mtchs)
if max is not None:
return spellcorrect[mtchs.index(max)]
else:
return None
# get correct spelling
map(lambda x: correctspell(x, good, thresh = 70), bad) # ['Barcelona', 'Amsterdam', 'Prague']
Run Code Online (Sandbox Code Playgroud)