Class 12 Programs
- 1.Input a welcome message and display it
- 2.Input two numbers and display the larger/smaller number
- 3.Enter two integers and perform all arithmetic operations
- 4.Generate patterns using nested loop
- 5.Input x and n, print sum of series
- 6.Check perfect number, Armstrong number or palindrome
- 7.Check if number is prime or composite
- 8.Display Fibonacci series terms
- 9.Compute GCD and LCM of two integers
- 10.Count vowels, consonants, uppercase, lowercase in string
- 11.Check palindrome string and convert case
- 12.Find largest/smallest number in list/tuple
- 13.Swap elements at even and odd locations
- 14.Search element in list/tuple
- 15.Find smallest and largest number from list
- 16.Dictionary with student marks above 75
- 17.Menu-driven student dictionary program
- 18.Choose 4 random lucky winners from 100 customers
- 19.String module operations menu
- 20.Friends phone directory dictionary operations
Quick Tips
- • Use isalpha() to check alphabetic characters
- • Remember both upper and lower case vowels
- • Handle file exceptions properly
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
- Open the text file in read mode.
- Initialize counters for vowels, consonants, uppercase, and lowercase characters to 0.
- Read the entire content of the file.
- Iterate through each character in the file content.
- 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
- Display the counts of vowels, consonants, uppercase, and lowercase characters.
- 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 closedMethod 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
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.
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.
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.
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.
How can you handle file not found error?
You can use try-except block to catch FileNotFoundError and handle it gracefully.