通过Levenstein Ratio删除Python列表中类似的字符串



我正试图通过计算python列表中相似单词之间的Levenstein比率来删除它们。如果比率>0.9这个词应该去掉。因此,我必须创建一个循环,遍历列表,将每个单词与其他单词进行比较,然后在比率过高时将其删除。不幸的是,我还没有完全弄清楚如何在python中实现这一点,因为我无法遍历列表并删除其内容。我的第一个天真想法是,像下面的代码一样,它不起作用,因为它跳过了一半的元素。如有任何帮助,我们将不胜感激。

word_list = ['asf', 'bcd', 'ase', 'cdf', 'asl']

此处的目标是删除元素"ase"one_answers"asl",因为它们类似于"asf"我的第一次尝试是这样的:

for word in word_list:
for x in word list:
if Levenshtein.ratio(word, x) >= 0.9:
word_list.remove(word)

使用difflib可以匹配列表中的类似字符串。然后移除类似的字符串。

import difflib
word_list = ['asf', 'bcd', 'ase', 'cdf', 'asl']
close_match = difflib.get_close_matches('asf', word_list)
close_match.remove('asf')
result = []
for i in word_list:
if i not in close_match:
result.append(i)
print(result)
>>> ['asf', 'bcd', 'cdf']

您可以尝试以下内容:

# Output list
output = []
for word in word_list:
for x in word_list:
# Change our logic, and look for values below 0.9 - Then add those to our output list
if not Levenshtein.ratio(word, x) >= 0.9 and (word not in output):
output.append(word)

最新更新