我有以下代码:
from math import sqrt
from collections import Counter
def forSearch():
words = {'bit':{1:3,2:4,3:19,4:0},'shoe':{1:0,2:0,3:0,4:0},'dog':{1:3,2:0,3:4,4:5}, 'red':{1:0,2:0,3:15,4:0}}
search = {'bit':1,'dog':3,'shoe':5}
num_files = 4
file_relevancy = Counter()
c = sqrt(sum([x**2 for x in search.values()]))
for i in range(1, num_files+1):
words_ith_val = [words[x][i] for x in search.keys() ]
a = sum([search[key] * words[key][i] for key in search.keys()])
b = sqrt(sum([x**2 for x in words_ith_val]))
file_relevancy[i] = (a / (b * c))
return [x[0] for x in file_relevancy.most_common(num_files)]
print forSearch()
但是,对于包含在搜索中但不包含在单词中的单词,这有一个问题:
我想说这样的话:
for i in range(1, num_files+1):
if corresponding key in words cannot be found
insert it and make its value = 0
words_ith_val = [words[x][i] for x in search.keys() ]
那就行了?你知道吗
除非别人有更好的建议?你知道吗
^{}
这个代码呢:
在您的代码中,您可以尝试
您可以使用defaultdict:
这将初始化一个字典,其中键是在access上创建的,默认值为0。也可以使用其他类型:
它们将用一个空字典/列表初始化。 也可以使用工厂方法覆盖默认值。详见https://docs.python.org/2/library/collections.html#collections.defaultdict。你知道吗
相关问题 更多 >
编程相关推荐