Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a counter to a file in order?

Tags:

python

I need to write a counter to a file in order of most occurring to least occurring but I am having a little trouble. When I print the counter it prints in order but when I call counter.items() and then write it to a file it writes them out of order.

I am trying to make it like this:

word      5
word2     4
word3     4
word4     3
like image 565
Alex Brashear Avatar asked Dec 06 '22 07:12

Alex Brashear


2 Answers

I'd suggest you to use collections.Counter and then Counter.most_common will do what you're looking for:

Demo:

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

Write this to a file:

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

help on 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)]
like image 136
Ashwini Chaudhary Avatar answered Dec 08 '22 19:12

Ashwini Chaudhary


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

should work fine :)

dictionaries have no order which is what a counter is so you must sort the item list if you want it in some order... in this case ordered by the "value" rather than the "key"

like image 44
Joran Beasley Avatar answered Dec 08 '22 20:12

Joran Beasley