Richard Dabel
Richard Dabel

Reputation: 25

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

Upvotes: 1

Views: 75

Answers (2)

pylang
pylang

Reputation: 44485

How do I modify my code so my code will have output like my expected result

from collections import Counter


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

counts = Counter(lists).most_common(4)
print ("Sort by 4 words that have highest occurance")
for word, count in counts:
    print("{} : {}".format(word.title(), count))

Output

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

Note: no rule is specified for ordering entries with duplicate values, e.g. Book and Rain

Upvotes: 1

prudhvi Indana
prudhvi Indana

Reputation: 829

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

Upvotes: 2

Related Questions