我用python创建了一个简单的单词统计程序,它读取一个文本文件,统计词频,并将结果写入另一个文件。问题是,当单词重复时,程序会写入同一单词的初始计数和最终计数。例如,如果单词" hello“重复3次,程序将在输出中写入3个hello实例,如下所示:
词频统计
你好-1
你好-2
你好-3
代码是:
counts ={}
for w in words:
counts[w] = counts.get(w,0) + 1
outfile.write(w+','+str(counts[w])+'\n')'任何帮助都将不胜感激。我是python的新手。
发布于 2014-02-19 15:21:08
解决这个问题的实际方法是使用Counter,如下所示:
>>> from collections import Counter
>>> words = ['b','b','the','the','the','c']
>>> Counter(words).most_common()
[('the', 3), ('b', 2), ('c', 1)]另一种解决方法是使用defaultdict,其工作方式与上面的Counter示例类似:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for word in words:
... d[word] += 1
...
>>> d
defaultdict(<type 'int'>, {'the': 3, 'b': 2, 'c': 1})无论如何计算单词,都只能在计算完所有单词后才能写入文件;否则,每次" count“都会写入一次,一旦单词出现不止一次,输出就会加倍。
因此,首先收集计数,然后将它们写出来。
发布于 2014-02-19 15:26:45
让代码工作的方法:
counts ={}
for w in words:
counts[w] = counts.get(w,0) + 1
for w in counts:
outfile.write(w+','+str(counts[w])+'\n')但我认为Burhan Khalid建议使用Counter是解决问题的更好方法。
发布于 2014-02-19 15:16:19
您是否考虑过先将频率计数存储在您的程序中,然后在最后将其全部写入?这肯定比为每一次计数重写输出文件简单。
https://stackoverflow.com/questions/21873511
复制相似问题