决定删除并再次询问,只是更容易!请不要投票,因为已经采取了人们所说的话。
我有两个嵌套词典: -
wordFrequency = {'bit':{1:3,2:4,3:19,4:0},'red':{1:0,2:0,3:15,4:0},'dog':{1:3,2:0,3:4,4:5}}
search = {1:{'bit':1},2:{'red':1,'dog':1},3:{'bit':2,'red':3}}
第一个字典链接单词文件编号和它们在该文件中出现的次数。第二个包含将单词与当前搜索中出现的次数相关联的搜索。
我想提取某些值,以便对于每次搜索,我可以计算文件中出现的单词次数与它们在搜索中出现的次数除以其大小之间的标量乘积,然后查看哪个文件最多类似于当前的搜索即(搜索中的单词1出现*文件中的单词1出现)+(搜索中的单词2出现*文件中的单词2出现)等然后将搜索字典返回到文件编号列表,最相似首先,最不相似的最后一次。
预期输出是字典:
{1:[4,3,1,2],2:[1,2,4,3]}
等
键是搜索号,该值是最相关的文件列表。
(这些可能实际上并不正确。)
这就是我所拥有的: -
def retrieve():
results = {}
for word in search:
numberOfAppearances = wordFrequency.get(word).values()
for appearances in numberOfAppearances:
results[fileNumber] = numberOfAppearances.dot()
return sorted (results.iteritems(), key=lambda (fileNumber, appearances): appearances, reverse=True)
很抱歉没有它只是说wdir =然后是.py文件所在的目录。
整个Retrieve.py文件:
from collections import Counter
def retrieve():
wordFrequency = {'bit':{1:3,2:4,3:19,4:0},'red':{1:0,2:0,3:15,4:0},'dog': {1:3,2:0,3:4,4:5}}
search = {1:{'bit':1},2:{'red':1,'dog':1},3:{'bit':2,'red':3}}
results = {}
for search_number, words in search.iteritems():
file_relevancy = Counter()
for word, num_appearances in words.iteritems():
for file_id, appear_in_file in wordFrequency.get(word, {}).iteritems():
file_relevancy[file_id] += num_appearances * appear_in_file
results[search_number] = [file_id for (file_id, count) in file_relevancy.most_common()]
return results
我正在使用Spyder GUI / IDE for Anaconda Python 2.7,只需按下绿色播放按钮,输出就是:
WDIR = '/用户/丹尼/桌面'
关于幅度,例如,对于搜索号3和文件1,它将是:
sqrt(2 ^ 2 + 3 ^ 2 + 0 ^ 2)* sqrt(3 ^ 2 + 0 ^ 2 + 3 ^ 2)
答案 0 :(得分:0)
这是一个开始:
from collections import Counter
def retrieve():
results = {}
for search_number, words in search.iteritems():
file_relevancy = Counter()
for word, num_appearances in words.iteritems():
for file_id, appear_in_file in wordFrequency.get(word, {}).iteritems():
file_relevancy[file_id] += num_appearances * appear_in_file
results[search_number] = [file_id for (file_id, count) in file_relevancy.most_common()]
return results
print retrieve()