我需要按照大多数发生的顺序写一个文件计数器,但是我遇到了一些麻烦.当我打印计数器时,它会按顺序打印,但是当我调用counter.items()然后将其写入文件时,它会将它们按顺序写入.
我想这样做:
word 5 word2 4 word3 4 word4 3
... 谢谢!
我建议你使用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)]