我有一个字符串列表作为查询和一些其他字符串列表的趋势。我想将查询与其他列表进行比较,并提取它们之间的相似性分数。
示例:
query = ["football", "basketball", "martial arts", "baseball"]
list1 = ["apple", "football", "basketball court"]
list2 = ["ball"]
list3 = ["martial-arts", "baseball", "banana", "food", "doctor"]
我现在在做什么,我对结果不满意是对它们的绝对比较。
score = 0
for i in query:
if i in list1:
score += 1
score_of_list1 = score*100//len(list1)
我找到了一个可以帮助我fuzzywuzzy的图书馆,但我在想是否有其他建议方法。
答案 0 :(得分:5)
如果您正在寻找一种方法来查找字符串之间的相似性,那么SO question建议使用Levenshtein distance作为一种方法。
准备好了solution,它也存在于Natural Language Tool Kit库中。
天真整合将是(我只是随意使用结果。显然没有意义):
#!/usr/bin/env python
query = ["football", "basketball", "martial arts", "baseball"]
lists = [["apple", "football", "basketball court"], ["ball"], ["martial-arts", "baseball", "banana", "food", "doctor"]]
from random import random
def fake_levenshtein(word1, word2):
return random()
def avg_list(l):
return reduce(lambda x, y: x + y, l) / len(l)
for l in lists:
score = []
for w1 in l:
for w2 in query:
score.append(fake_levenshtein(w1, w2))
print avg_list(score)
祝你好运。