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.
# Python program to count number of vowels, # newlines and character in textfile def counting(filename): # Opening the file in read mode txt_file = open(filename, "r") # Initialize three variables to count number of vowels, # lines and characters respectively vowel = 0 line = 0 character = 0 # Make a vowels list so that we can # check whether the character is vowel or not vowels_list = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] # Iterate over the characters present in file for alpha in txt_file.read(): # Checking if the current character is vowel or not if alpha in vowels_list: vowel += 1 # Checking if the current character is # not vowel or new line character elif alpha not in vowels_list and alpha != "\n": character += 1 # Checking if the current character # is new line character or not elif alpha == "\n": line += 1 # Print the desired output on the console. print("Number of vowels in ", filename, " = ", vowel) print("New Lines in ", filename, " = ", line) print("Number of characters in ", filename, " = ", character) # Calling the function counting which gives the desired output counting('Myfile.txt')
Output:
Number of vowels in MyFile.txt = 23 New Lines in MyFile.txt = 2 Number of characters in MyFile.txt = 54
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.