2016-06-10 100 views
0

所以我有下面的代碼來計算文本文件中的字數。我想用出現次數最多的單詞對輸出進行排序。這如何實現?如何排序字數的輸出

ally = open("alice.txt", "r") 
wordcount={} 
for word in ally.read().split(): 
    if word not in wordcount: 
     wordcount[word] = 1 

    else: 
     wordcount[word] += 1 

for k,v, in wordcount.items(): 
    print(k,v) 

回答

1

您可以查看使用operator.itemgetter()排序詞典:

from operator import itemgetter 

wordcount = {'test': 1, 'hello': 3, 'test2':0} 

sortedWords = sorted(wordcount.items(), key=itemgetter(1), reverse = True) 

輸出:

>>> sortedWords 
[('hello', 3), ('test', 1), ('test2', 0)] 
2

只需使用Counter。它將縮短您的代碼並獲得您想要的訂購。

從文檔引用:

A計數器是用於計數可哈希對象的字典子類。它是一個無序集合,其中元素作爲字典鍵存儲,並且它們的計數作爲字典值存儲在 中。計數允許爲任何整數值,包括零或負計數。櫃檯類 類似於其他語言的箱包或多配套。

>>> c = Counter(['eggs', 'ham']) 
>>> c['bacon']        # count of a missing element is zero 
0 
0

這應該爲你做: -

ally = open("alice.txt", "r") 
wordcount={} 
for word in ally.read().split(): 
    if word not in wordcount: 
     wordcount[word] = 1 
    else: 
     wordcount[word] += 1 

for k,v, in sorted(wordcount.items(), key=lambda words: words[1], reverse = True): 
    print(k,v)