Read a text file and display the number of vowels, consonants, uppercase and lowercase characters in the file program in Python, C and Java

“Read a text file and display the number of vowels, consonants, uppercase and lowercase characters in the file” is a standard file-handling practical in Class 12 computer science. The program opens a text file, reads its text, visits every character and keeps four counters. In this post you will see the program in Python, C and Java, a character-by-character dry run, eight other ways to write it, and answers to common questions. Use the interactive tool below to type your own file contents and watch each character being checked.

★ Count Vowels, Consonants, Uppercase and Lowercase in a File

Type the contents of story.txt and watch the program check every character and update the counters.

Graphical view

Code

Output

What You Will Learn

Problem Statement

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

Suppose story.txt contains these two lines:

Welcome to My Website
Always Learn Python in Class 12

The program should print:

Vowels: 14
Consonants: 28
Uppercase: 7
Lowercase: 35

The interactive tool above accepts up to 3 lines and 40 characters, so that you can follow every step.

The Idea: One Loop and Four Counters

First, read the whole file into one string with f.read(). A string is a row of characters, and a for loop can visit them one by one. Make four counters, all starting at 0: vowels, consonants, upper and lower. For each character:

  • If it is not a letter (a space, digit, symbol or new line), ignore it. The test is ch.isalpha().
  • If it is a letter, decide vowel or consonant. A vowel is one of aeiouAEIOU. Every other letter is a consonant.
  • Independently, decide uppercase or lowercase with ch.isupper().

Notice that every letter is counted twice, once in a vowel/consonant counter and once in an upper/lower counter. So vowels + consonants always equals upper + lower, which is the total number of letters. This gives you a quick check of your own answer: in the output above, 14 + 28 = 42 = 7 + 35.

The interactive tool shows each character as a box. Green means vowel, blue means consonant and a faded box is not a letter.

The Program

Logic:

  • Open the file, read all its text into text, and close the file.
  • Set the four counters to 0.
  • For every character, skip it if it is not a letter.
  • Add 1 to vowels or consonants, and add 1 to upper or lower.
  • Print the four counters.

Python program

f = open("story.txt", "r")
text = f.read()
f.close()
vowels = 0
consonants = 0
upper = 0
lower = 0
for ch in text:
    if ch.isalpha():
        if ch in "aeiouAEIOU":
            vowels = vowels + 1
        else:
            consonants = consonants + 1
        if ch.isupper():
            upper = upper + 1
        else:
            lower = lower + 1
print("Vowels:", vowels)
print("Consonants:", consonants)
print("Uppercase:", upper)
print("Lowercase:", lower)

Output

Vowels: 14
Consonants: 28
Uppercase: 7
Lowercase: 35
C program
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
    FILE *f = fopen("story.txt", "r");
    int ch, vowels = 0, consonants = 0, upper = 0, lower = 0;
    while ((ch = fgetc(f)) != EOF) {
        if (isalpha(ch)) {
            if (strchr("aeiouAEIOU", ch) != NULL) {
                vowels++;
            } else {
                consonants++;
            }
            if (isupper(ch)) {
                upper++;
            } else {
                lower++;
            }
        }
    }
    fclose(f);
    printf("Vowels: %d\n", vowels);
    printf("Consonants: %d\n", consonants);
    printf("Uppercase: %d\n", upper);
    printf("Lowercase: %d\n", lower);
    return 0;
}
Vowels: 14
Consonants: 28
Uppercase: 7
Lowercase: 35

In C, fgetc() reads one character at a time, and it returns the special value EOF at the end of the file. Because EOF is -1, the variable must be an int, not a char. The functions isalpha() and isupper() come from ctype.h, and strchr() from string.h checks whether the character is in the string of vowels.

Java program
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class CountCharacters {
    public static void main(String[] args) throws IOException {
        String text = new String(Files.readAllBytes(Paths.get("story.txt")));
        int vowels = 0, consonants = 0;
        int upper = 0, lower = 0;
        for (char ch : text.toCharArray()) {
            if (Character.isLetter(ch)) {
                if ("aeiouAEIOU".indexOf(ch) != -1) {
                    vowels++;
                } else {
                    consonants++;
                }
                if (Character.isUpperCase(ch)) {
                    upper++;
                } else {
                    lower++;
                }
            }
        }
        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
        System.out.println("Uppercase: " + upper);
        System.out.println("Lowercase: " + lower);
    }
}
Vowels: 14
Consonants: 28
Uppercase: 7
Lowercase: 35

Save this file as CountCharacters.java. Files.readAllBytes() reads the whole file, and toCharArray() turns the string into an array of characters for the loop. Character.isLetter() and Character.isUpperCase() do the tests, and indexOf() returns -1 when the character is not found in the vowel string.

Dry Run

Let us trace the text Hello World (11 characters). The last four columns show the counters after each character.

IndexchLetter?KindCasevowelsconsonantsupperlower
0Hyesconsonantupper0110
1eyesvowellower1111
2lyesconsonantlower1212
3lyesconsonantlower1313
4oyesvowellower2314
5spaceno––2314
6Wyesconsonantupper2424
7oyesvowellower3425
8ryesconsonantlower3526
9lyesconsonantlower3627
10dyesconsonantlower3728

The final counts are 3 vowels (e, o, o), 7 consonants (H, l, l, W, r, l, d), 2 uppercase letters (H and W) and 8 lowercase letters. The space at index 5 is skipped because it is not a letter.

Other Ways to Write the Program

Method 2: Convert to lowercase first

text.lower() turns every letter to lowercase, so the vowel string can be just "aeiou". This version counts vowels and consonants only, because the case information is lost after the conversion.

with open("story.txt", "r") as f:
    text = f.read()
vowels = 0
consonants = 0
for ch in text.lower():
    if ch.isalpha():
        if ch in "aeiou":
            vowels = vowels + 1
        else:
            consonants = consonants + 1
print("Vowels:", vowels)
print("Consonants:", consonants)
Vowels: 14
Consonants: 28

Method 3: Read line by line

Instead of read(), you can loop over the file and then over the characters of each line. This uses less memory for a very large file. The program is the same as before, with one more loop, and it also shows the compact += operator and the chained assignment vowels = consonants = upper = lower = 0.

vowels = consonants = upper = lower = 0
with open("story.txt", "r") as f:
    for line in f:
        for ch in line:
            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)
Vowels: 14
Consonants: 28
Uppercase: 7
Lowercase: 35

Method 4: sum() with a generator

Each sum(1 for ...) counts the characters that pass a test. Consonants are the letters that are not vowels, so we calculate them as letters - vowels.

with open("story.txt", "r") as f:
    text = f.read()
vowels = sum(1 for ch in text if ch in "aeiouAEIOU")
letters = sum(1 for ch in text if ch.isalpha())
upper = sum(1 for ch in text if ch.isupper())
lower = sum(1 for ch in text if ch.islower())
print("Vowels:", vowels)
print("Consonants:", letters - vowels)
print("Uppercase:", upper)
print("Lowercase:", lower)
Vowels: 14
Consonants: 28
Uppercase: 7
Lowercase: 35

Method 5: Count each vowel separately

The string method count() returns how many times a character occurs.

with open("story.txt", "r") as f:
    text = f.read().lower()
for v in "aeiou":
    print(v, text.count(v))
a 4
e 5
i 2
o 3
u 0

Method 6: collections.Counter

Counter builds a dictionary of counts in one step.

from collections import Counter
with open("story.txt", "r") as f:
    text = f.read().lower()
counts = Counter(ch for ch in text if ch in "aeiou")
print(counts)
Counter({'e': 5, 'a': 4, 'o': 3, 'i': 2})

Method 7: Count digits, spaces and symbols too

Characters that are not letters can be grouped as well. Here we count digits, spaces (including new lines) and all other symbols.

digits = spaces = others = 0
with open("story.txt", "r") as f:
    for ch in f.read():
        if ch.isdigit():
            digits += 1
        elif ch == " " or ch == "\n":
            spaces += 1
        elif not ch.isalpha():
            others += 1
print("Digits:", digits)
print("Spaces and new lines:", spaces)
print("Other symbols:", others)
Digits: 2
Spaces and new lines: 10
Other symbols: 0

Method 8: Handle a missing file

try:
    with open("missing.txt", "r") as f:
        text = f.read()
except FileNotFoundError:
    print("File not found. Check the file name and folder.")
File not found. Check the file name and folder.
C: case-insensitive version with tolower() and a file check
#include <stdio.h>
#include <ctype.h>
int main() {
    FILE *f = fopen("story.txt", "r");
    if (f == NULL) {
        printf("File not found\n");
        return 1;
    }
    int ch, vowels = 0, consonants = 0;
    while ((ch = fgetc(f)) != EOF) {
        if (isalpha(ch)) {
            ch = tolower(ch);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                vowels++;
            } else {
                consonants++;
            }
        }
    }
    fclose(f);
    printf("Vowels: %d\n", vowels);
    printf("Consonants: %d\n", consonants);
    return 0;
}
Vowels: 14
Consonants: 28

This C program checks that fopen() did not return NULL, converts each letter to lowercase with tolower() and compares it with the five vowels. It prints the vowel and consonant counts only.

Common Mistakes

  • Forgetting the capital vowels. Checking only "aeiou" misses A, E, I, O and U. With our file the program prints 13 instead of 14 vowels:
f = open("story.txt", "r")
text = f.read()
vowels = 0
for ch in text:
    if ch in "aeiou":
        vowels = vowels + 1
print("Vowels:", vowels)
Vowels: 13
  • Counting everything that is not a vowel as a consonant. Spaces, digits and new lines are not vowels, but they are not consonants either. The test ch not in "aeiouAEIOU" gives a wrong, larger answer:
f = open("story.txt", "r")
text = f.read()
consonants = 0
for ch in text:
    if ch not in "aeiouAEIOU":
        consonants = consonants + 1
print("Consonants:", consonants)
Consonants: 40

The correct number of consonants is 28. Always check isalpha() first.

  • Reading the file twice. After f.read() the file position is at the end, so a second read() returns an empty string:
f = open("story.txt", "r")
text = f.read()
text = f.read()
print(len(text))
0
  • Using char for EOF in C. EOF is -1, which does not fit a char on every system. Declare int ch.
  • Forgetting to initialise the counters. A counter must start at 0 before the loop, or Python raises a NameError and C gives garbage values.
  • Opening the file with “w”. Mode "w" empties the file immediately. Use "r" for reading.
  • Wrong file location. If story.txt is not in the folder from which the program runs, you get FileNotFoundError (or NULL in C).

Practice Questions

  1. Also display the number of digits and the number of spaces in the file.
  2. Display the percentage of vowels among all the letters.
  3. Display how many times each vowel appears (Method 5), ignoring the case.
  4. Display the most frequent letter in the file.
  5. Display the number of words, lines and characters in the file.
  6. Copy the file into a new file, converting lowercase letters to uppercase and uppercase to lowercase. Hint: ch.swapcase().
  7. Count the lines that start with a vowel.

Frequently Asked Questions

How do you count vowels and consonants in a text file in Python?

Read the file with f.read() and loop through the characters. For each letter (ch.isalpha()), add 1 to vowels if it is in "aeiouAEIOU", otherwise add 1 to consonants.

How do you count uppercase and lowercase letters in a file?

Use ch.isupper() and ch.islower() inside the same loop. Every letter is either uppercase or lowercase, so you can use an if and an else after checking isalpha().

Are spaces and digits counted as consonants?

No. A consonant is a letter that is not a vowel. Spaces, digits, punctuation and new lines are not letters, so the program skips them by testing isalpha() first.

Why is vowels + consonants equal to upper + lower?

Both pairs split the same group, the letters, into two parts. Vowels plus consonants is every letter, and uppercase plus lowercase is every letter, so the two totals must match.

What do isalpha(), isupper() and islower() do?

isalpha() is true for letters only. isupper() is true for an uppercase letter, and islower() for a lowercase letter. In C the same functions are in ctype.h, and Java has Character.isLetter(), isUpperCase() and isLowerCase().

What is the difference between read(), readline() and readlines()?

read() returns the whole file as one string, readline() returns one line, and readlines() returns a list of all lines. For this program read() is the simplest, because you only need the characters.

Why is a new line character not counted?

The new line \n is a character in the file, but it is not a letter, so isalpha() is false and the program skips it, just like a space.

What if the file is empty?

The loop never runs, so all four counters stay 0 and the program prints zeros. The program does not fail.

How do I do this in C?

Open the file with fopen(), read each character with fgetc() until EOF, test it with isalpha(), isupper() and strchr(), and close the file with fclose(). Store the character in an int, not a char.

How do I do this in Java?

Read the file with Files.readAllBytes(Paths.get("story.txt")), convert it to a string, and loop over toCharArray(). Use Character.isLetter() and Character.isUpperCase(), and declare throws IOException on main.

Does the program work with Hindi or other languages?

This school program is written for English letters. Python and Java treat many other alphabets as letters but have no concept of a “vowel” in the string aeiouAEIOU, so those letters would be counted as consonants. Plain C with isalpha() works with ASCII text only.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top