2012-08-02 91 views
2

這應該是一個簡單的問題,但我無法用頭圍住它。我有一本名爲TD的字典。的:的TD {鍵{KEY2值}}是{1:{u'word':3, u'next':2, u'the':2},2:{...}...}其中key1是文檔,key2是一個字一個文檔中和value是詞在文檔中出現的次數,使用Counter方法獲得的。在python中更新我的字典

我有大量的文檔,以便每個文檔在TD中的條目:

TD = {1:{u'word':2, u'next':1, u'the':5,...}, 
     2:{u'my':4, u'you':1, u'other':2,...}, 
     ... 
     168:{u'word':1, u'person':1, u'and':8,...}} 

我現在想要做的是檢查{1{...}}每個單詞,看它是否出現在其他文件,重複這個過程爲每個文件。對於每個文檔的詞出現在,freq增加1我有一個名爲Score新詞典看起來應該像這樣的:

{1:{u'word':score, u'next':score,...}, 2:{u'my':score, u'you':score,...}...} 

要獲得這本字典:

Score={} 
count = 0 
for x,i in TD[count].iteritems(): 
    freq=1 
    num=1 
    for y in TD[num].keys(): 
     if word in TF[num].keys(): 
      freq+=1 
     num+=1 
    Score[num]={x:(i*freq)} 
    num+=1 

這是給我下面的輸出:

{1:{u'word':score}, 2:{u'next':score}, 3:{u'the':score}...} 

應該是:

{1:{u'word':score, u'next':score, u'the':score,...}...} 

我認爲這個問題是與線Score[num]={x:(i*freq)}

回答

3

使用dict views來查找文檔之間的交叉點,那麼計數器計數其頻率:

Score = {} 
for id, document in TD.iteritems(): 
    counts = Score[id] = Counter() 
    for otherid, otherdocument in TD.iteritems(): 
     if otherid == id: 
      continue # Skip current document 
     counts.update(document.viewkeys() & otherdocument.viewkeys()) 

在分數的每個條目將是一個數文檔中每個單詞出現在其他文檔中的頻率。

如果您還需要在當前文檔中包括字數(count + 1),只需刪除if otherid == id測試。

在自己的代碼,你一頭霧水numcount,但在Python中,你通常不需要手動增加在任何情況下循環計數器。

+0

這不起作用,因爲我也需要這個詞。如果我這樣做,它會是'{u'word':score}',但我需要它''{1:{u'word':score,u'next':score,...},2 {...} ...} – adohertyd 2012-08-02 17:59:24

+0

更新;使用['dict.viewkeys()'](http://docs.python.org/library/stdtypes.html#dict.viewkeys)和一個內部循環來計算文檔中的詞頻。 – 2012-08-02 18:08:00

+0

仍然不是我想要做的。我只需要看看這個詞是否出現在其他文檔中,無論多頻繁。我的原始字典「TD」包含每個文檔的字數。新的字典存儲TD的價值*這個詞出現在文檔的數量 – adohertyd 2012-08-02 18:11:37