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:
        word_frequency[w]+=1
    else:
        word_frequency[w]=1

But using Collections module our task is more simplified.

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

Using Counter from Collections

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

For more understanding of how this module works visit /https://stackabuse.com/introduction-to-pythons-collections-module/.
Also if you have any doubts or questions please comment on this post so that I can get back to you.

Leave a Reply

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