Python Program to Count the Frequency of Words in a File

In this example, we will write a python program to find the frequency of the words present in the file. To better understand this example, make sure you have knowledge of the following tutorials:-

Loading…

Python Program to Count the Frequency of Words in a File

Let us assume we have an about.txt file that contains the following paragraph.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla consectetur auctor elit id ornare. Aenean magna quam, sodales quis mollis quis, blandit vel leo. Aliquam non aliquam nulla. Nulla facilisi. Nulla eu commodo urna. Fusce malesuada purus non mollis vulputate. Integer nec sem enim.

The code for the program is:-
from collections import Counter
def word_count(fname):
        with open(fname) as f:
                return Counter(f.read().split())

print("Number of words in the file :",word_count("about.txt"))

The output of the above program is:-

Number of words in the file : Counter({‘Nulla’: 3, ‘consectetur’: 2, ‘mollis’: 2, ‘non’: 2, ‘Lorem’: 1, ‘ipsum’: 1, ‘dolor’: 1, ‘sit’: 1, ‘amet,’: 1, ‘adipiscing’: 1, ‘elit.’: 1, ‘auctor’: 1, ‘elit’: 1, ‘id’: 1, ‘ornare.’: 1, ‘Aenean’: 1, ‘magna’: 1, ‘quam,’: 1, ‘sodales’: 1, ‘quis’: 1, ‘quis,’: 1, ‘blandit’: 1, ‘vel’: 1, ‘leo.’: 1, ‘Aliquam’: 1, ‘aliquam’: 1, ‘nulla.’: 1, ‘facilisi.’: 1, ‘eu’: 1, ‘commodo’: 1, ‘urna.’: 1, ‘Fusce’: 1, ‘malesuada’: 1, ‘purus’: 1, ‘vulputate.’: 1, ‘Integer’: 1, ‘nec’: 1, ‘sem’: 1, ‘enim.’: 1})

Here the collections counter is used to count the number of unique words in the file which returns the dictionary of words with the count frequnecy.

Loading…