Python program to count the occurrences of a word in a text file
In this post, you will learn how to count the occurrences of a particular word or each word in a text file using the Python programming language. Generally, it is required in the development process to count the occurrences of each word or a particular word in a text document or a given sentence. Here, we have mentioned different ways to achieve this.
Count occurrences of each word in a given file using dictionary
To accomplish this task, we use a dictionary object that stores the word as the key and its count as the corresponding value. We loop through each word in the given file and add it to the dictionary with count 1. If the word is already present in the dictionary, we increase its count by 1. Suppose we have the following text file, 'demo.txt'.
Quiz Competition Participants
Priska Abhishek John Henry
Chess Competition Participants
John Prince Priska Henry
Make sure the text file is in the same directory as the Python file.
def word_count(str):
# Create an empty dictionary
counts = dict()
words = str.split()
# Loop through each line of the file
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
# Open the file in read mode
file = open("demo.txt", "r")
#read content of file to string
data = file.read()
# Print the number of occurrences of word
print( word_count(data))
Output of the above code-
{'Quiz': 1, 'Competition': 2, 'Participants': 2, 'Priska': 2, 'Abhishek': 1, 'John': 2, 'Henry': 2, 'Chess': 1, 'Prince': 1}
Count occurrences of each word in a given sentence using dictionary
In the given Python program, we first read the sentence from the user using a built-in function input() and store it in a variable, and then we utilize a dictionary object that stores the word as the key and its count as the corresponding value. We loop through each word and count the occurrences of each word, adding them to the dictionary with count 1.
def word_count(str):
# Create an empty dictionary
counts = dict()
words = str.split()
# Loop through each line of the file
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
# get input from user
string = input("Please enter sentence: ")
# Print the number of occurrences of word
print( word_count(string))
Output of the above code-
Pleae enter sentence: Python is a high level open source programming language. Python is an extremely powerful language.
{'Python': 2, 'is': 2, 'a': 1, 'high': 1, 'level': 1, 'open': 1, 'source': 1, 'programming': 1, 'language.': 2, 'an': 1, 'extremely': 1, 'powerful': 1}
Count occurrences of a word in a given file using count() function
In the above Python program, we got the occurrence of each word, but what if we need to get the occurrence of a particular word in a file? Here is the simplest solution to this. We can use the count() function to count the occurrences of a particular word in a given file.
Suppose we have a text file 'demo.txt' that contains the following text-
Python is a high level open source programming language. Python is an extremely powerful language.
#get file object reference to the file
file = open("C:\workspace\python\data.txt", "r")
# read content of file to string
data = file.read()
# get number of occurrences of the substring in the string
occurrences = data.count("python")
print('Number of occurrences of the word :', occurrences)
Output of the above code-
Number of occurrences of the word : 2
Related Articles
Reverse pyramid pattern in Python
Fizzbuzz program in Python
Python split string by comma
Python alive progress bar
Python progress bar tqdm
Python language translator code
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Python program to sort words in alphabetical order
How to remove stop words in Python
Create word cloud using Python
Python iterate list with index
Python Spell Checker Program
Python random choice
Python dict inside list
Remove character from string Python
Python split multiple delimiters
Extract text from image using Python
Find the stop words in nltk Python
Convert speech to text in Python
Python Text to Speech
Read and write a file using Django