Sorted Word frequency count using python

WARNING: This example requires Python 2.7 or higher.

Python’s built-in Counter object is exactly what you’re looking for. Counting words is even the first example in the documentation:

>>> # Tally occurrences of words in a list
>>> from collections import Counter
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

As specified in the comments, Counter takes an iterable, so the above example is merely for illustration and is equivalent to:

>>> mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue']
>>> cnt = Counter(mywords)
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

Leave a Comment