【问题标题】:Creating a simple searching program创建一个简单的搜索程序
【发布时间】:2015-01-18 22:54:32
【问题描述】:

决定删了再问,比较简单!请不要像人们所说的那样投反对票。

我有两个嵌套字典:-

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

我正在使用 Anaconda Python 2.7 的 Spyder GUI/IDE,只需按下绿色播放按钮,输出为:

wdir='/Users/danny/Desktop'

  • 编辑 2

关于大小,例如,对于搜索号 3 和文件 1,它将是:

sqrt (2^2 + 3^2 + 0^2) * sqrt (3^2 + 0^2 + 3^2)

【问题讨论】:

标签: python search dictionary text-processing


【解决方案1】:

这是一个开始:

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 = '' (文件路径在引号中)。打印结果?
  • 您运行脚本的具体情况如何?能否将整个文件内容复制到问题中?
  • 显示在原始问题中:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-18
  • 2019-03-27
  • 2017-12-02
  • 2021-10-27
相关资源
最近更新 更多