我有以下代码:如何处理在Python字典找不到钥匙
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() ]
那么它应该工作?
除非其他人有更好的建议吗?
您的'words'变量声明应该能够使用数组语法:'words = {'bit':[3,4,19,0]'shoe':[0,0,0,0], '狗':[3,0,4]}。你可能想坚持0-索引(从0开始计数,而不是1) – 2014-11-24 08:12:02
我不允许改变单词的方式。 – DannyBoy 2014-11-24 08:36:56