Sometimes, we want to get the item frequency count in Python.
In this article, we’ll look at how to get the item frequency count in Python.
How to get the item frequency count in Python?
To get the item frequency count in Python, we can use the collections
module.
For instance, we write:
from collections import Counter
words = "apple banana apple strawberry banana lemon"
counts = Counter(words.split())
print(counts)
We use the Counter
class with the words
string split into a list with split
by the spaces.
This lets us get the count of each word in a string.
Therefore, counts
is Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})
.
Conclusion
To get the item frequency count in Python, we can use the collections
module.