2015-04-23 134 views
1

我已經使用xlrd將Excel表單值附加到列表中。我打電話給名單a_master。我有一個帶有單詞的文本文件,我想計算出現在這個列表中的出現次數(我稱這個文件字典和他們的每行1個單詞)。下面是代碼:使用Python計算出現在列表中的單詞的出現次數

with open("dictionary.txt","r") as f: 
for line in f: 
    print "Count " + line + str((a_master).count(line)) 

出於某種原因,不過,伯爵回來與零存在在文本文件中的每個字計數。如果我寫出來的計數這些詞我自己:

print str((a_master).count("server")) 

它計算的出現沒有任何的疑難問題也按順序嘗試

print line 

,看它是否是看到的話dictionary.txt文件正確,它是。

+0

你能否提供該文件的例子? – ka2m

+0

這是http://stackoverflow.com/questions/8742732/python-number-of-word-occurrences –

+0

@ tommy.carstensen的副本:不是一個確切的副本。請閱讀我的答案。 – Abhijit

回答

1

從文件中讀取的行以換行符結束。最後也可能有空白。這是更好地做一個查找

with open("dictionary.txt","r") as f: 
    for line in f: 
     print "Count " + line + str((a_master).count(line.strip())) 

注意理想之前去掉所有的空白,搜索列表是線性的,也有可能在大多數情況下是最佳的。我認爲collections.Counter適合你所描述的情況。

重新詮釋您的列表作爲一本字典,其中的關鍵是項目和值使其通過collections.Counter是出現如下圖所示

a_master = collections.Counter(a_master) 

,你可以重新編寫代碼爲

from itertools import imap 
with open("dictionary.txt","r") as f: 
    for line in imap(str.strip, f): 
     print "Count {} {}".format(line, a_master[line]) 
+0

完美的作品,非常感謝! – Danny

+0

@丹尼:如果這回答你的問題,請考慮接受它。 – Abhijit

+0

實際上還有一個問題。爲了統計列表中單詞的出現次數,我將列表中的每個單詞分開。但是如果我想計算「軟件定義網絡」的發生情況呢?我將如何去做這件事?我需要重寫如何在dictionary.txt文件中出現該句子嗎?我的txt文件混合了單個單詞和句子。 – Danny

0

使用collections.Counter()

import re 
import collections 
words = re.findall(r'\w+', open('dictionary.txt').read().lower()) 
collections.Counter(words) 

爲什麼爲t他的問題的方式標記xlrd?