Practical 8: Program to read data from a file and calculate the percentage of vowels and consonants in the file content.
Problem Statement
Write a Python program to read data from a file and calculate the percentage of vowels and consonants in the file content.
Solution Code
# Program to calculate the percentage of vowels and consonants in a file
# Function to calculate vowels and consonants
def calculate_vowel_consonant_percentage(filename):
try:
# Open the file in read mode
with open(filename, "r") as file:
content = file.read().lower() # Read file content and convert to lowercase
# Define vowels
vowels = "aeiou"
total_chars = len(content) # Total number of characters in file
vowel_count = sum(1 for char in content if char in vowels) # Count vowels
consonant_count = sum(1 for char in content if char.isalpha() and char not in vowels) # Count consonants
# Avoid division by zero
if total_chars == 0:
print("The file is empty.")
return
# Calculate percentages
vowel_percentage = (vowel_count / total_chars) * 100
consonant_percentage = (consonant_count / total_chars) * 100
# Display results
print(f"Total Characters: {total_chars}")
print(f"Vowel Count: {vowel_count}, Percentage: {vowel_percentage:.2f}%")
print(f"Consonant Count: {consonant_count}, Percentage: {consonant_percentage:.2f}%")
except FileNotFoundError:
print("Error: The specified file was not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Call the function with the filename
calculate_vowel_consonant_percentage("sample.txt")
Output
If sample.txt contains:
Python programming is fun and powerful. File handling is an important concept.
The output might be:
Total Characters: 78
Vowel Count: 21, Percentage: 26.92% Consonant Count: 44, Percentage: 56.41%
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 4 Practical 8 solution where we have written Python program to read data from a file and calculate the percentage of vowels and consonants in the file content.
- Reading the File
- The program opens the file in read mode (r) and reads its content.
- content.lower() ensures all text is processed in lowercase to avoid case mismatches.
- Counting Vowels and Consonants
- A set of vowels (“aeiou”) is defined.
- sum(1 for char in content if char in vowels) counts vowels in the file.
- sum(1 for char in content if char.isalpha() and char not in vowels) counts consonants.
- Calculating Percentages
- The percentage is calculated using the formula: percentage=(count/total characters)×100
- The result is displayed with two decimal places.
- Error Handling
- The program handles FileNotFoundError if the file is missing.
- It also catches other exceptions to prevent crashes.
Key Concepts Learned
- File Handling (open(), read(), with statement)
- Using with open(…) ensures proper file handling and automatic closure.
- String Processing (lower(), isalpha())
- lower() is used for uniform case processing.
- isalpha() ensures only letters are considered (ignoring spaces, digits, and symbols).
- Exception Handling (try-except)
- The program prevents crashes by handling missing files and unexpected errors.