HomeComputer SciencePractical ProgramsClass 12Vowels Consonants Uppercase Lowercase

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

AIM

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

ALGORITHM

  1. Open the text file in read mode.
  2. Initialize counters for vowels, consonants, uppercase, and lowercase characters to 0.
  3. Read the entire content of the file.
  4. Iterate through each character in the file content.
  5. For each character:
    • Check if it's an alphabetic character
    • If uppercase, increment uppercase counter
    • If lowercase, increment lowercase counter
    • If vowel (a, e, i, o, u), increment vowel counter
    • If consonant (alphabetic but not vowel), increment consonant counter
  6. Display the counts of vowels, consonants, uppercase, and lowercase characters.
  7. Close the file.

PROGRAM

# Open the file in read mode
file = open("sample.txt", "r")

# Initialize counters
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0

# Read the entire content of the file
content = file.read()

# Define vowels
vowel_list = "aeiouAEIOU"

# Iterate through each character
for char in content:
    if char.isalpha():  # Check if character is alphabetic
        if char.isupper():
            uppercase += 1
        if char.islower():
            lowercase += 1
        
        if char in vowel_list:
            vowels += 1
        else:
            consonants += 1

# Display the results
print("Character Analysis of the file:")
print(f"Number of vowels: {vowels}")
print(f"Number of consonants: {consonants}")
print(f"Number of uppercase characters: {uppercase}")
print(f"Number of lowercase characters: {lowercase}")

# Close the file
file.close()

Content of sample.txt file:

Hello World!

This is a SAMPLE file for Testing.

Python Programming is FUN.

OUTPUT

Character Analysis of the file:

Number of vowels: 15

Number of consonants: 25

Number of uppercase characters: 12

Number of lowercase characters: 28

RESULT

The program executed successfully and displayed the count of vowels, consonants, uppercase characters, and lowercase characters from the text file.

KEY POINTS

  • isalpha(): Checks if a character is alphabetic (a-z, A-Z)
  • isupper(): Checks if a character is uppercase
  • islower(): Checks if a character is lowercase
  • Vowels: a, e, i, o, u (both uppercase and lowercase)
  • Consonants: All alphabetic characters except vowels

PROGRAM VARIATIONS

Method 1: Using 'with' statement (Recommended)

# Using 'with' statement for better file handling
with open("sample.txt", "r") as file:
    content = file.read()
    
    vowels = consonants = uppercase = lowercase = 0
    vowel_list = "aeiouAEIOU"
    
    for char in content:
        if char.isalpha():
            if char.isupper():
                uppercase += 1
            if char.islower():
                lowercase += 1
            
            if char in vowel_list:
                vowels += 1
            else:
                consonants += 1
    
    print(f"Vowels: {vowels}")
    print(f"Consonants: {consonants}")
    print(f"Uppercase: {uppercase}")
    print(f"Lowercase: {lowercase}")
# File is automatically closed

Method 2: Using functions for better organization

def analyze_file(filename):
    vowels = consonants = uppercase = lowercase = 0
    vowel_list = "aeiouAEIOU"
    
    try:
        with open(filename, "r") as file:
            content = file.read()
            
            for char in content:
                if char.isalpha():
                    if char.isupper():
                        uppercase += 1
                    if char.islower():
                        lowercase += 1
                    
                    if char in vowel_list:
                        vowels += 1
                    else:
                        consonants += 1
        
        return vowels, consonants, uppercase, lowercase
    
    except FileNotFoundError:
        print("File not found!")
        return 0, 0, 0, 0

# Call the function
v, c, u, l = analyze_file("sample.txt")
print(f"Vowels: {v}, Consonants: {c}")
print(f"Uppercase: {u}, Lowercase: {l}")

COMMON ERRORS & SOLUTIONS

FileNotFoundError

Make sure the file "sample.txt" exists in the same directory as your Python script.

Incorrect vowel counting

Remember to include both uppercase and lowercase vowels in your vowel list.

Counting non-alphabetic characters

Always check if a character is alphabetic using isalpha() before counting.

VIVA QUESTIONS

  1. What does isalpha() function do?

    The isalpha() function returns True if all characters in the string are alphabetic (a-z, A-Z) and there is at least one character.

  2. How do you check if a character is a vowel?

    You can check if a character is in the vowel list "aeiouAEIOU" using the 'in' operator.

  3. What's the difference between isupper() and islower()?

    isupper() returns True if the character is uppercase, while islower() returns True if the character is lowercase.

  4. Why do we use read() method?

    The read() method reads the entire content of the file as a single string, making it easy to iterate through each character.

  5. How can you handle file not found error?

    You can use try-except block to catch FileNotFoundError and handle it gracefully.