Write a Python Program to Count The Frequency of Words in a File

Hi, in this blog lets learn Python Program to Count The Frequency of Words in a File. Given a text file containing words and lines, you should try writing a program to count words frequency of occurrence and print it.


count words frequency



This program is divided into two phases

1) Open the file in read mode, get the data, clean the data or any special characters.

2) Split the data and frame dictionary having word as key and frequency as value. Count occurrence of each word and increment value and print it.


Phase 1: Open file and read the contents

fd = open("sample.txt","r")
data = fd.read()
fd.close()
special_char = "#,.!?"
for schar in special_char:
    if schar in data:
        data = data.replace(schar, "")

 

Phase 2:  Split the data and frame dictionary have frequency as value

words = data.split()
freq = {}
for word in words:
    if word in freq:
        freq[word] += 1
    else:
        freq[word] = 1
 
for key, value in freq.items():
    print(f"{key} occurs : {value} times")
 
 
Complete Program : 
 
fd = open("sample.txt","r")
data = fd.read()
fd.close()
special_char = "#,.!?"
for schar in special_char:
    if schar in data:
        data = data.replace(schar, "")
 
words = data.split()
freq = {}
for word in words:
    if word in freq:
        freq[word] += 1
    else:
        freq[word] = 1
 
for key, value in freq.items():
    print(f"{key} occurs : {value} times")

 

Run 1 : 

Contents of sample.txt 

Write a Python Program to Count The Frequency of Words in a File

OUTPUT :

Write occurs : 1 times
a occurs : 2 times
Python occurs : 1 times
Program occurs : 1 times
to occurs : 1 times
Count occurs : 1 times
The occurs : 1 times
Frequency occurs : 1 times
of occurs : 1 times
Words occurs : 1 times
in occurs : 1 times
File occurs : 1 times

 

Conclusion : Try to run the program by yourself and comment down below if you have any issue.

 

 

Post a Comment

0 Comments