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
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)]
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With