你如何按顺序写一个文件的计数器?

时间:2013-05-28 20:48:37

标签: python

我需要按照大多数发生的顺序写一个文件计数器,但是我遇到了一些麻烦。当我打印计数器时,它会按顺序打印,但是当我调用counter.items()然后将其写入文件时,它会将它们按顺序写入。

我想这样做:

word      5
word2     4
word3     4
word4     3

... 谢谢!

2 个答案:

答案 0 :(得分:9)

我建议您使用collections.Counter,然后Counter.most_common会执行您要找的内容:

演示:

>>> c = Counter('abcdeabcdabcaba')
>>> c.most_common()
[('a', 5), ('b', 4), ('c', 3), ('d', 2), ('e', 1)]

将此内容写入文件:

c = Counter('abcdeabcdabcaba')
with open("abc") as f:
    for k,v in  c.most_common():
        f.write( "{} {}\n".format(k,v) )

Counter.most_common上的帮助:

>>> Counter.most_common?
Docstring:
List the n most common elements and their counts from the most
common to the least.  If n is None, then list all element counts.

>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]

答案 1 :(得分:1)

from operator import itemgetter
print sorted( my_counter.items(),key=itemgetter(1),reverse=True)

应该可以正常工作:)

字典没有计数器的顺序,所以你必须按照某种顺序对项目列表进行排序......在这种情况下,按“值”而不是“键”排序