ByteBoard Notes Notes

Read a text file and display the number of vowels, consonants, uppercase and lowercase characters

Computer Science XII · Experiment 07 of 29 · Python

★ CBSE suggested12-CSPython programs
Expt. No.07
Page No.14

Counting characters in a text file

Aim

To write a Python program that reads a text file and displays the number of vowels, consonants, uppercase and lowercase characters in it.

Concepts used

Algorithm

  1. Set four counters to 0.
  2. Open the file in read mode and read it into a string.
  3. For each character, skip it if it is not a letter.
  4. If it is in "aeiouAEIOU", add 1 to vowels, else to consonants.
  5. If it is uppercase, add 1 to upper, else to lower.
  6. Display the four counts.

Program

# Count vowels, consonants, uppercase and# lowercase characters in a text file def count_chars(filename):    vowels = consonants = upper = lower = 0    with open(filename, "r") as f:        data = f.read()    for ch in data:        if ch.isalpha():            if ch in "aeiouAEIOU":                vowels += 1            else:                consonants += 1            if ch.isupper():                upper += 1            else:                lower += 1    print("Vowels      :", vowels)    print("Consonants  :", consonants)    print("Uppercase   :", upper)    print("Lowercase   :", lower) count_chars("story.txt")

A marked line continues the line above it. In your file, write it on the same line.

Input file

story.txt3 lines
Python was created by Guido van Rossum.
It is Easy to Read and Write.
CBSE Class XII uses Python 3.

Output

$ python count_chars.py
Vowels : 28 Consonants : 48 Uppercase : 16 Lowercase : 60

✓ Printed by running this program, not typed by hand.

Result

The program read story.txt and counted 76 letters: 28 vowels and 48 consonants, of which 16 are uppercase and 60 lowercase. Spaces, digits and full stops were not counted.

Viva voce: what the examiner may ask

01Why open the file with with instead of plain open()?

The with clause closes the file on its own when the block ends, even if an error occurs.

02What is the default mode of open()?

"r", read mode for a text file.

03Why check isalpha() first?

Without it, spaces, digits, full stops and newlines would all be counted as consonants.

04How are read(), readline() and readlines() different?

read() returns the whole file as one string, readline() returns one line, and readlines() returns a list of all lines.

05What happens if story.txt does not exist?

Python raises FileNotFoundError. You can handle it with try-except.

Variations for the lab test

  1. Also count digits and spaces in the file.
  2. Display the lines that start with a vowel.
  3. Count the words in the file using split().
! Common mistake Writing else: consonants += 1 without the isalpha() check makes the consonant count too high.
Back to the 12-CS index