by BehindJava
Write a program to Count the Occurrences of a Word in a Text File in Python
In this tutorial we are going to learn about counting the Occurrences of a Word in a Text File in Python.
Python Program to Count the Occurrences of a Word in a Text File
fname = input("Enter file name: ")
word=input("Enter word to be searched:")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
Explanation
- User must enter a file name and the word to be searched.
- The file is opened using the open() function in the read mode.
- A for loop is used to read through each line in the file.
- Each line is split into a list of words using split().
- Another for loop is used to traverse through the list and each word in the list is compared with the word provided by the user.
- If both the words are equal, the word count is incremented.
- The final count of occurrences of the word is printed.