2014-04-03 76 views
2

爲什麼我總是收到屬性的錯誤不會消失

AttributeError: 'dict_keys' object has no attribute 'sort' 

或我的代碼?我怎樣才能解決這個問題?

import string 

infile = open('alice_in_wonderland.txt', 'r') 

text = infile.readlines() 

counts = {} 

for line in text: 
    for word in line: 
    counts[word] = counts.get (word, 0) +1 
''' 
if word != " ": 
if word != ".": 
'''   

word_keys = counts.keys() 
word_keys.sort() 

infile.close() 

outfile = open("alice_words.txt", 'w') 
outfile.write("Word \t \t Count \n") 
outfile.write("======================= \n") 
for word in word_keys: 
outfile.write("%-12s%d\n" % (word.lower(), counts[word])) 
outfile.close() 

我不確定還有什麼要做。

回答

8

要生產鍵的排序列表,使用方法:

word_keys = sorted(counts) 

代替。這適用於Python 2和3.

在Python 3中dict.keys()不返回列表對象,而是一個dictionary view object。您可以在該對象上撥打list(),但sorted()更直接,並且可以節省您兩個額外的電話。

我看到你似乎在一個文件中計算單詞;如果是這樣的話,那你就是字符,而不是單詞; for word in line:迭代一個字符串,因此word被分配了一行中的單個字符。

您應該使用collections.Counter()代替:

from collections import Counter 

counts = Counter 

with open('alice_in_wonderland.txt') as infile: 
    for line in infile: 
     # assumption: words are whitespace separated 
     counts.update(w for w in line.split()) 

with open("alice_words.txt", 'w') as outfile: 
    outfile.write("Word \t \t Count \n") 
    outfile.write("======================= \n") 
    for word, count in counts.most_common(): 
     outfile.write("%-12s%d\n" % (word.lower(), counts[word])) 

該代碼使用文件對象的上下文管理器(與with語句)讓它們自動關閉。 Counter.most_common()方法負責爲我們排序,而不是按鍵,但通過字數。

+0

哇,非常感謝,你是男人。出於某種原因,我正試圖修復9-11行。 – user3490645