Richard Dabel Richard Dabel - 1 year ago 124
Python Question

How to sort word frequency in a list (but not all of them printed) in Python

I have to count the word frequency in a list using python, but what I want is I want to count the words according to its occurance, but I dont't want to print it all

For the example, i have this list

lists = ["me","sleep","love","me","love","love","love","rain","love","me","me","rain","book","book","rain","book","catch","watch"]


If I use this:

from collections import Counter
counts = Counter(lists)
print(counts)


it will come result:

Counter({'love': 5, 'me': 4, 'rain': 3, 'book': 3, 'sleep': 1, 'catch': 1, 'watch': 1})


But my expected result is:

Sort by 4 words that have highest occurance
Love : 5
Me : 4
Rain : 3
Book : 3


So "sleep","catch" and "watch" will not be included in my result
How do I modify my code so my code will have output like my expected result, I mean sort by XX words that have highest value of occurance.

Thank you very much

Answer Source
from collections import Counter
counts = Counter(lists).most_common(4)
print ("Sort by 4 words that have highest occurance")
print ("\n".join([str(x)+ " : " + str(y) for x,y in counts]))

output:

Sort by 4 words that have highest occurance
love : 5
me : 4
rain : 3
book : 3
sleep : 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download