Program to count the total number of consonants in a file

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

				
					#readcontent.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.

				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”).
  2. Read the data and split it into words using file.read().split().
  3. Create a list of vowels.
  4. Create a count variable and assign its value equal to 0.
  5. Use a for loop to iterate over the words.
  6. Use a nested for loop to iterate over the characters in the word.
  7. Check whether the character is not in the vowels list using an if statement.
  8. If yes then add 1 to the count variable.
  9. Print the output.
				
					# Open file
file = open('readcontent.txt')
# Read data and converting into words
words = file.read().split()
# Create a list of vowels
vowels = ['a','e','i','o','u','A','E','I','O','U']
# Create count variable
count = 0
# Iterate over words
for word in words:
# Iterate over characters in the word
    for char in word:
    # Check for consonants
        if char not in vowels:
    # Add 1 to the count variable for each consonant
            count += 1
# Print output
print("Total number of consonants in the file: ",count)
				
			

Output :

Total number of consonants in the file: 48

 

 

count the total number of vowels in a file.

remove all the lines that contain the character ‘t’ in a file and write it to another file.

Leave a Comment