我需要按照大多数发生的顺序写一个文件计数器,但是我遇到了一些麻烦.当我打印计数器时,它会按顺序打印,但是当我调用counter.items()然后将其写入文件时,它会将它们按顺序写入.
我想这样做:
word 5
word2 4
word3 4
word4 3
Run Code Online (Sandbox Code Playgroud)
... 谢谢!
Ash*_*ary 11
我建议你使用collections.Counter然后Counter.most_common会做你想要的:
演示:
>>> c = Counter('abcdeabcdabcaba')
>>> c.most_common()
[('a', 5), ('b', 4), ('c', 3), ('d', 2), ('e', 1)]
Run Code Online (Sandbox Code Playgroud)
将此内容写入文件:
c = Counter('abcdeabcdabcaba')
with open("abc") as f:
for k,v in c.most_common():
f.write( "{} {}\n".format(k,v) )
Run Code Online (Sandbox Code Playgroud)
帮助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)]
Run Code Online (Sandbox Code Playgroud)