2012-10-23 40 views
0

我正在運行以下代碼來計算文本文件中出現單詞的次數。我的字典有什麼問題?

def print_words(filename): 
    f = open(filename, 'rU') 
    dict={} 
    for line in f: 
     words=line.split() 
     for word in words: 
      if dict.get(word): 
       dict[word]=dict[word]+1 
      else: 
       dict[word]=1 
    ke = sorted(dict.keys()) 
    for k, v in ke: print k, v 

字典文件應該包含每個單詞和它的計數。我能夠很好地工作。但我沒有排序

+8

我以爲你不小心的細節。 –

+2

btw,'dict'是一個不好的變量名,因爲它會覆蓋'dict'類型。 – Marian

回答

1

sorted(dict.keys())返回一個排序列表,只是鍵。您的for循環錯誤地期望在同一列表中找到值。請嘗試下面的代碼:

for k in ke: 
    print k, dict[k] 
1

而不是

ke = sorted(dict.keys()) 
for k, v in ke: print k, v 

嘗試:

for k in sorted(dict.keys()): 
    print k, dict[k] 

sorted(dict.keys())僅返回鍵的排序列表(因爲這些是你給它)。

2

其他答案指出了問題。如果您使用Python 2.7+,使用collections模塊中的Counter類可以更簡單地完成此操作。

from collections import Counter 

def print_words(filename): 
    with open(filename, 'rU') as f: 
     counts = Counter(f.read().split()) 
    for k, v in sorted(counts.items()): 
     print k, v 
0

根據什麼更重要的是 - 訂單或計數 - 你可以使用從collections module

OrderedDict要麼ordered dictionarycounter dictionary記得在它們被添加的順序的元素;計數器 - 計數的元素

對於前者,你可以做這樣的事情

>>> words = open(filename).read().split() 
>>> counters = OrderedDict([(word, words.count(word)) 
          for word in sorted(list(set(words)))]) 

您將得到有序字典設有專櫃 - 剛剛在2號線。

+0

該解決方案的效率很差。 'words.count(word)'是一個O(n)操作,每個單詞都會被調用,所以整個事情就是O(n ** 2),即使只有一個「單詞」話。使用'Counter'是一種更高效的O(n)解決方案。如果您希望先查看單詞,首先使用Counter對單詞進行計數,然後使用['itertools.unique_everseen'配方]對單詞進行迭代(http://docs.python.org/library/itertools .html#食譜)並將計數添加到OrderedDict中。 –

+0

@lazyr - 沒有想到它。感謝您指出 – volcano

1

對於2.5和2.6兼容的解決方案,使用defaultdict

from collections import defaultdict 
counter = defaultdict(int) 

for word in f.read().split(): 
    counter[word] += 1 

這將返回一個字典(子類實際,但使用的方法相同),在那裏你可以查找counter['someword'](即回報一個整數)。

工作原理:如果所請求的鍵不存在,則使用給定函數的返回值創建它。在這種情況下,int(),這是0。請參閱上面鏈接的文檔中的示例部分。

+0

好的建議,但不回答OP的實際問題。 –

+0

當然,因爲這已經被回答:)我只是把它作爲Counter答案的補充。(並且它將他的代碼縮短兩行;)) – Marian

+0

它只縮短了代碼,因爲您忘記了打開文件並且不打印排序的計數。實際上,這需要一個額外的*行:'counter = defaultdict(int)'。無論如何,我認爲你至少會修復文件打開。 –