如何将计数器按顺序写入文件?

2024-04-26 05:23:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要按照最常见到最不常见的顺序为一个文件写一个计数器,但我遇到了一点小麻烦。当我打印计数器时,它会按顺序打印,但当我调用counter.items()然后将其写入文件时,它会按顺序将其写入

我正试着这样做:

word      5
word2     4
word3     4
word4     3

Tags: 文件顺序counter计数器itemswordword2word3
2条回答

我建议您使用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", 'w') 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)]
from operator import itemgetter
print sorted( my_counter.items(),key=itemgetter(1),reverse=True)

应该很好:)

字典没有计数器的顺序,因此如果您希望项目列表按某种顺序排序,则必须对其进行排序。。。在这种情况下,按“值”而不是“键”排序

相关问题 更多 >