Program to count of a specific word in a file

In this python file program, we will count of a specific word in a file. Let’s consider we have readcontent.txt file with the below content. We will get a count of a specific word in a file with the help of the below-given steps.

				
					# ReadContent.txt
This is Python Programming Language
Its very Python easy to learn to and 
Best language for Python beginners
				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”,”r”).
  2. Read the data and split it into words using file.read().split().
  3. Create a variable count and assign its value equal to 0.
  4. Use for loop to iterate over words.
  5. If the word is equal to python then add 1 to the count variable.
  6. Print the respective output.
				
					# Open file with read mode
file = open('readcontext.txt','r')
# Read the data in the file and convert it into words
words = file.read().split()
# Create count variable
count = 0
# Iterate over the words
for word in words:
# Match word
    if word == 'Python':
        count += 1
# Print output
print("Count of python in the file: ",count)
				
			

Output :

Count of Python in the file: 3

 

 

find the longest word in a file.

read a random line from a file.

Leave a Comment