如何按顺序为文件编写计数器?

2024-05-14 14:50:28 发布

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

我需要写一个计数器到一个文件,按发生的次数从多到少的顺序,但我有一个小麻烦。当我打印计数器时,它会按顺序打印,但当我调用counter.items()然后将其写入文件时,它会按顺序写入它们。

我想这样做:

word      5
word2     4
word3     4
word4     3

。。。 谢谢!


Tags: 文件顺序counter计数器items次数wordword2
2条回答
from operator import itemgetter
print sorted( my_counter.items(),key=itemgetter(1),reverse=True)

应该工作正常:)

字典没有计数器的顺序,所以如果您希望按某种顺序对项目列表排序。。。在这种情况下,按“值”而不是“键”排序

我建议您使用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)]

相关问题 更多 >

    热门问题