![](/img/trans.png)
[英]Optimizing counting occurences of a list of words in a given string (Python)
[英]Counting occurences of words that appear in a list using Python
我已經使用xlrd將excel工作表值附加到列表中。 我將列表稱為a_master。 我有一個文本文件,其中包含一些單詞,我想計算出現在此列表中的單詞的數量(我將此文件詞典稱為“字典”,每行1個單詞)。 這是代碼:
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文件中的單詞。
從文件讀取的行以換行符終止。 末尾可能還會有空白。 最好在執行查找之前先去除所有空格
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])
import re
import collections
words = re.findall(r'\w+', open('dictionary.txt').read().lower())
collections.Counter(words)
為什么這個問題被標記為xlrd?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.