Count the number of vowels in a file using Python

Count the number of vowels in a file using Python

Problem description :

The program reads a text file entered by the user and counts the number of vowels in the text file.

Prerequisite : Files concepts

Procedure :
  1. Start.
  2. Read the file.
  3. Store the file in a string.
  4. initialize a count variable.
  5. Iterate through the string.
  6. check if the character is a vowel.
  7. increment the count variable.
  8. End.
Input file :

demofile.txt
Techieebytes is a tech blog where you can find lot of programming exercises and solutions. The programming exercise can be solved in any of the programming language. In this program we are going to  count the number of vowels in a text file.

Code :

#Method 1 (using or operator)
#open the text file in read mode
f = open("demofile.txt", "r")
#read the file and the contents will be stored as string in s.
s = f.read()
#initialize count variable
count = 0
for i in s:
        #if the letter is a vowel
if(i=="a" or i=="e" or i=="i" or i=="o" or i=="u"):
                #increment count
count+=1
#print vowel count
print("Number of vowels = ",count)
#Method 2 (using list)
#open the text file in read mode
f = open("demofile.txt", "r")
#read the file and the contents will be stored as string in s.
s = f.read()
#initialize count variable
count = 0
for i in s:
        #if the letter is in the list containing vowels
if(i in ["a","e","i","o","u"]):
                #increment count
count+=1
#print vowel count
print("Number of vowels = ",count)

#Method 3 (using set)
#open the text file in read mode
f = open("demofile.txt", "r")
#read the file and the contents will be stored as string in s.
s = f.read()
#initialize count variable
count=0
#create a set of vowels
vowel = set("aeiou")
for i in s:
        #if the letter in vowel set
if(i in vowel):
                #increment count
count+=1
#print vowel count
print("Number of vowels = ",count)

Sample input :

count vowels in a file
demofile.txt


Sample output :

Count vowels in file
Output






Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

What's your name, Tuple - HackerRank solution in python