我有以下代码:
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() ]
那它应该有用吗?
除非其他人有更好的建议吗?
答案 0 :(得分:2)
import collections
D = collections.defaultdict(int)
D['foo'] = 42
print D['foo'], D['bar']
答案 1 :(得分:2)
您可以使用defaultdict:
from collections import defaultdict
d = defaultdict(int)
这将初始化一个字典,其中密钥是在访问时创建的,默认值为0.您也可以使用其他类型:
defaultdict(dict)
defaultdict(list)
它们将使用空字典/列表进行初始化。 您还可以使用工厂方法覆盖默认值。有关详细信息,请参阅https://docs.python.org/2/library/collections.html#collections.defaultdict。
答案 2 :(得分:0)
这段代码怎么样:
if key not in words:
words[key] = {k+1: 0 for k in range(num_files)}
在您的代码中,您可以尝试
for key in search.keys():
if key not in words:
words[key] = {k+1: 0 for k in range(num_files)}
words_ith_val = [words[key][k + 1] for k in range(num_files)]