2013-09-27 104 views
1

我是一個嘗試構建簡單程序的初學者程序員。它應該計算文件中的每一個單詞,但正如我寫的那樣,它只計算最後一行文本。開始的字計數程序只產生python中最後一行的輸出

tm = open('myfile.txt', 'r') 
for line in tm: 
    line = line.replace ('\n', '') 
    line = line.strip() 
    line = line.translate(None, '!#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~') 
    line = line.lower() 
    line = line.split(' ') 
    list = line 
dict ={} 
for word in list: 
    dict[word]=1 
if word in dict: 
    count = dict[word] 
    count += 1 
    dict[word] = count 
else: 
    dict[word]=1 
for word,count in dict.iteritems(): 
    print word + ": " + str(count) 

我的輸出是這

about: 1 
to: 1 
subscribe: 1 
hear: 1 
new: 1 
our: 1 
newsletter: 1 
email: 1 
ebooks: 2 

任何幫助表示讚賞

+0

你可以跳過'.replace()','.strip()'和'.lower()'調用:'open('myfile.txt','rb')作爲文件:print collections.Counter (字的文件中的行在line.translate(string.maketrans(string.ascii_uppercase,string.ascii_lowercase),string.punctuation).split())。most_common()' – jfs

回答

1

在你的代碼替換該行一500頁文檔 :

list = line # that's not how you add elements to a list! 

有了這個其他:

list.extend(line) 

而且它會是一個好主意,重命名爲lstlist變量,因爲list是內置的,這是一個壞主意,將其覆蓋。 dict同樣的事情,你不應該用它作爲變量名稱。

另一個好主意:使用Counter對象跟蹤詞頻,這比手動更新字典的計數器值容易得多。在您創建和填充字典的整個代碼塊可以通過這個來代替:

from collections import Counter 
d = Counter(lst) # notice the suggested variable names 
0

正如奧斯卡說,你應該將數組項添加到您的列表,而不是取代它。 嘗試使用擴展而不是追加。

list.extend(line) 

您可以一次將數組中的所有項目添加到列表中。

追加用於添加單個項目列表。