Python 创建一个简单的搜索程序
决定删除并再次询问,只是更容易!请不要投反对票,因为我们已经接受了人们一直在说的话 我有两个嵌套字典:-Python 创建一个简单的搜索程序,python,search,dictionary,text-processing,Python,Search,Dictionary,Text Processing,决定删除并再次询问,只是更容易!请不要投反对票,因为我们已经接受了人们一直在说的话 我有两个嵌套字典:- 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}} 第一个词典将单词链接到一个文件号以及它们在该文件中出现的次数。第二个包含将单词链
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在文件中出现)+(word 2在搜索中出现*word 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文件所在的目录
- 编辑
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
我正在为Anaconda Python 2.7使用Spyder GUI/IDE,只需按下绿色播放按钮,输出为:
wdir='/Users/danny/Desktop'
- 编辑2
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()
可能的重复我不会这么说,这是更基本的方式。你能帮忙吗?我仍然没有得到任何输出,只有wdir=再次?我测试了这个代码,它工作了。什么是
wdir=
?你打印了结果吗?它只是说wdir=''(文件路径在引号中)。打印结果?您如何准确运行脚本?能否将整个文件内容复制到问题?如原始问题所示:)