Finding word frequency using Collections module in Python

In this post I am going to discuss how to use Collections module in Python. In simple words collections are nothing but containers that has list, tuple, dict, set etc.

From collections I am going to explain how to use defaultdict and counter subclasses.

Let’s take a basic example:
Suppose we want to get the frequency of words from a text. We do the following.

word_frequency = {}
for words in sent.split(" "):
    if words in word_frequency:

But using Collections module our task is more simplified.

from collections import defaultdict
word_frequency = defaultdict(int)
for words in sent.split(" "):

Using Counter from Collections

from collections import Counter
word_frequency = Counter()
for words in sent.split(" "):

For more understanding of how this module works visit /
Also if you have any doubts or questions please comment on this post so that I can get back to you.

Start a Conversation

Your email address will not be published. Required fields are marked *