TYL P3 - Files(count of vowels, consonants, line numbers)

TYL P3 - Files (count of vowels, consonants, line numbers)

9.      Write a python program to count the number of vowels and consonants in a file.

Read line by line
set up a counter variable for consonants and vowels.
convert the case of a line to lower or upper
traverse each character in the line
check if there are alphabetic, using isalpha()
then check if the character is a vowel or not.

Debugging
print out the contents of the line and debug if the output is not as expected.
Try out with a small file, then move to a large file.

Program:

fname = input("Enter a file name:")

try:
    fhand = open(fname)
except:
    print("Invalid File")
    exit()

vowels=0
consonants=0
for line in fhand:
    line = line.lower()
   # print('Debug:',line)
    for ch in line:
        if ch.isalpha():
            if ch in 'aeiou':
                vowels+=1
            else:
                consonants+=1

print('Consonants:',consonants)
print('Vowels:', vowels)

Output:

Enter a file name:romeo-full.txt
Consonants: 4089
Vowels: 2614


10.    Write a program in python to print the file contents with line number using file.


Do a rstrip() of each line before printing to avoid an extra line whilst printing.
Set up a counter variable to track the line count.

Program:

fname = input("Enter a file name:")
try:
    fhand = open(fname)
except:
    print("Invalid File")
    exit()

lineCount=1

for line in fhand:
    line=line.rstrip()
    print(lineCount,": ",line)

Output:

Enter a file name:test.txt
1 :  Hi there
2 :  How are you

Comments

Popular posts from this blog

TYL - Food Corner Program

Classes and objects solution

TYL - Salary Hike - Python Problem