2014-11-20 28 views
2

決定刪除並再次詢問,只是更容易!請不要像人們一直在說的那樣投票。創建一個簡單的搜索程序

我有兩個嵌套的字典: -

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}} 

第一詞典鏈接的話,他們出現在文件中的文件數量和次數。第二個包含將單詞與它在當前搜索中出現的次數關聯起來的搜索。

我想要提取某些值,以便對於每次搜索,我可以計算單詞在文件中出現的次數與出現在搜索中的次數之間的標量積,然後再除以它們的大小,然後查看哪個文件是最近似於當前的搜索ie(搜索詞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的蟒蛇Python 2.7版,只需按下綠色的播放按鈕,輸出是:

WDIR = '/用戶/丹尼/桌面'

  • 編輯2

在問候的幅度,例如,搜索號3和文件1這將是:

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

+0

可能重複的[如何索引文件的快速搜索?](http://stackoverflow.com/questions/844277/how-do-you-index-files-for-fast-searches) – 2014-11-20 22:13:15

+0

我不會這麼說,這是方式更基本。你能幫忙嗎? – DannyBoy 2014-11-20 22:14:14

+0

我不遵循? – DannyBoy 2014-11-20 22:21:17

回答

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() 
+0

我仍然沒有得到任何輸出,只有wdir =再次? – DannyBoy 2014-11-20 22:54:27

+0

我測試了這個代碼,它的工作原理。什麼是'wdir ='?你打印結果了嗎? – Tzach 2014-11-20 22:56:04

+0

它只是說wdir =''(文件路徑在引用中)。打印結果? – DannyBoy 2014-11-20 23:01:30

相關問題