Python Program to Count Vowels, Lines, Characters in Text File
In this article, we are going to create a python program that counts vowels, lines, and a number of characters present in a particular text file.
Approach
- We have to open the file using open() function in python.
- Then make three variables, vowel, line and character to count the number of vowels, lines, and characters respectively.
- Make a list of vowels so that we can check whether the character is a vowel or not.
- When the count hits the ‘\n’ character we have to increase our line variable means a new line in the file.
- After that iterate over the characters of the file and count the vowels, lines, and characters.
Below is the full Implementation:
Python3
def counting(filename):
txt_file = open (filename, "r" )
vowel = 0
line = 0
character = 0
vowels_list = [ 'a' , 'e' , 'i' , 'o' , 'u' ,
'A' , 'E' , 'I' , 'O' , 'U' ]
for alpha in txt_file.read():
if alpha in vowels_list:
vowel + = 1
elif alpha not in vowels_list and alpha ! = "\n" :
character + = 1
elif alpha = = "\n" :
line + = 1
print ( "Number of vowels in " , filename, " = " , vowel)
print ( "New Lines in " , filename, " = " , line)
print ( "Number of characters in " , filename, " = " , character)
counting( 'Myfile.txt' )
|
Output:
Number of vowels in MyFile.txt = 23
New Lines in MyFile.txt = 2
Number of characters in MyFile.txt = 54
Text File:
Last Updated :
17 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...