我有以下代碼:如何處理在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