1

我看过一堆基本上做我正在做的事情的帖子,但不幸的是,我不确定为什么我不断得到不是我想要的输出。问题是,每当某个单词出现在我的 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()
4

2 回答 2

6

使用普通字典,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.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 个最大计数)。Counter的反向移植可用于 2.7 之前的 Python 版本。

defaultdict方法有一些缺点。仅仅访问缺失值会导致字典增长。此外,要使用它,您需要了解工厂函数并知道可以在不带参数的情况下调用int()以产生零值。

于 2012-09-04T17:17:16.003 回答
5

您的函数count_words每次调用时都会创建一个新字典(而不是仅添加到当前results字典。

但是,对于这样的事情,您可能需要考虑使用 a (这是模块中的Counter一个特殊功能:dictcollections

from collections import Counter
c = Counter()
for row in csv_reader:
    c.update(text.lower() for text in row)

print(c)
于 2012-09-04T17:12:17.597 回答