我看过很多帖子基本上都在做我正在做的事情,但不幸的是,我不确定为什么我总是得到不是我想要的输出。问题是,每当某个单词出现在我的 excel 文件中时,我都试图增加字典,但单词的每个实例都像我的代码当前一样被视为新单词。例如,“the”在我的文件中出现了约 50 次,但输出只是在许多不同的行上列出了“the”,每个实例的计数为“1”。实际上我希望“the”被列出一次,计数为“50”。非常感谢任何澄清!这是我的代码:
import csv
import string
filename = "input.csv"
output = "output1.txt"
def add_word(counts, word):
word = word.lower()
#the problem is here, the following line never runs
if counts.has_key(word):
counts[word] +=1
#instead, we always go to the else statement...
else:
counts[word] = 1
return counts
def count_words(text):
word = text.lower()
counts = {}
add_word(counts, word)
return counts
def main():
infile = open(filename, "r")
input_fields = ('name', 'country')
reader = csv.DictReader(infile, fieldnames = input_fields)
next(reader)
first_row = next(reader)
outfile = open(output, "w")
outfile.write("%-18s%s\n" %("Word", "Count"))
for next_row in reader:
full_name = first_row['name']
word = text.split(' ',1)[0]
counts = count_words(word)
counts_list = counts.items()
counts_list.sort()
for word in counts_list:
outfile.write("%-18s%d\n" %(word[0], word[1]))
first_row = next_row
if __name__=="__main__":
main()
请您参考如下方法:
使用普通字典,dict.get 方法非常适合计数:
>>> d = {}
>>> for color in 'red green blue green red red green'.split():
d[color] = d.get(color, 0) + 1
>>> d
{'blue': 1, 'green': 3, 'red': 3}
collections module提供了两种简化此代码的方法。
这是一个使用 collections.Counter 的
>>> from collections import Counter
>>> d = Counter()
>>> for color in 'red green blue green red red green'.split():
d[color] += 1
>>> d
Counter({'green': 3, 'red': 3, 'blue': 1})
还有 collections.defaultdict方法:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for color in 'red green blue green red red green'.split():
d[color] += 1
>>> d
defaultdict(<type 'int'>, {'blue': 1, 'green': 3, 'red': 3})
当您的输出需要是一个常规字典或者您使用的是旧版本的 Python 时,常规字典方法最适合。
Counter 方法易于使用,并且有许多实用程序非常适合对应用程序进行计数(例如,most_common() 方法列出了 n按排序顺序排列的最大计数)。 backport of Counter适用于 2.7 之前的 Python 版本。
defaultdict 方法有一些缺点。仅访问缺失值将导致字典增长。此外,要使用它,您需要了解工厂函数并知道可以在没有参数的情况下调用 int() 以生成零值。
