Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
Quick Tips
- • Import random module for number generation
- • Use randint(1, 6) for dice simulation
- • Handle user input validation properly
TEXT FILES IN PYTHON - Count the occurrences of word & Count number of vowels and consonants
AIM
To write a Python program to count the occurrences of a specific word in a text file and count the number of vowels and consonants in the file.
ALGORITHM
- Start
- Open the text file in read mode
- Read the entire content of the file
- Count occurrences of a specific word (case-insensitive)
- Initialize counters for vowels and consonants
- Iterate through each character in the file content
- Check if character is a vowel or consonant
- Increment respective counters
- Display the results
- Stop
PROGRAM
# Python program to count word occurrences and vowels/consonants in a file
def count_word_occurrences(filename, search_word):
"""Count occurrences of a specific word in the file"""
try:
with open(filename, 'r') as file:
content = file.read().lower() # Convert to lowercase for case-insensitive search
search_word = search_word.lower()
# Split content into words and count occurrences
words = content.split()
count = words.count(search_word)
return count
except FileNotFoundError:
print(f"Error: File '{filename}' not found!")
return 0
def count_vowels_consonants(filename):
"""Count vowels and consonants in the file"""
vowels = "aeiouAEIOU"
vowel_count = 0
consonant_count = 0
try:
with open(filename, 'r') as file:
content = file.read()
for char in content:
if char.isalpha(): # Check if character is alphabetic
if char in vowels:
vowel_count += 1
else:
consonant_count += 1
return vowel_count, consonant_count
except FileNotFoundError:
print(f"Error: File '{filename}' not found!")
return 0, 0
def create_sample_file():
"""Create a sample text file for demonstration"""
sample_content = """Python is a powerful programming language.
It is easy to learn and easy to use.
Python supports multiple programming paradigms.
Data science and machine learning are popular applications of Python.
Python has a large community of developers."""
with open('sample.txt', 'w') as file:
file.write(sample_content)
print("Sample file 'sample.txt' created!")
def display_file_content(filename):
"""Display the content of the file"""
try:
with open(filename, 'r') as file:
print(f"\n--- Content of {filename} ---")
print(file.read())
except FileNotFoundError:
print(f"Error: File '{filename}' not found!")
# Main program
if __name__ == "__main__":
print("TEXT FILE ANALYSIS - Word Count & Vowel/Consonant Count")
print("=" * 55)
filename = 'sample.txt'
# Create sample file
create_sample_file()
# Display file content
display_file_content(filename)
# Get word to search from user
search_word = input("\nEnter the word to search for: ")
# Count word occurrences
word_count = count_word_occurrences(filename, search_word)
print(f"\nThe word '{search_word}' appears {word_count} times in the file.")
# Count vowels and consonants
vowels, consonants = count_vowels_consonants(filename)
print(f"\nVowel count: {vowels}")
print(f"Consonant count: {consonants}")
print(f"Total alphabetic characters: {vowels + consonants}")
# Additional statistics
try:
with open(filename, 'r') as file:
content = file.read()
total_chars = len(content)
total_words = len(content.split())
total_lines = len(content.splitlines())
print(f"\n--- File Statistics ---")
print(f"Total characters: {total_chars}")
print(f"Total words: {total_words}")
print(f"Total lines: {total_lines}")
except FileNotFoundError:
print("Error reading file for statistics!")OUTPUT
TEXT FILE ANALYSIS - Word Count & Vowel/Consonant Count
=======================================================
Sample file 'sample.txt' created!
--- Content of sample.txt ---
Python is a powerful programming language.
It is easy to learn and easy to use.
Python supports multiple programming paradigms.
Data science and machine learning are popular applications of Python.
Python has a large community of developers.
Enter the word to search for: Python
The word 'Python' appears 3 times in the file.
Vowel count: 65
Consonant count: 98
Total alphabetic characters: 163
--- File Statistics ---
Total characters: 203
Total words: 32
Total lines: 5
CONCLUSION
The program successfully demonstrates text file analysis in Python. It counts word occurrences using case-insensitive search and analyzes character distribution by counting vowels and consonants. The program also provides additional file statistics including total characters, words, and lines.
VIVA QUESTIONS
How does the split() method work in Python?
The split() method splits a string into a list of words based on whitespace (default) or a specified delimiter.
What is the difference between count() and find() methods?
count() returns the number of occurrences of a substring, while find() returns the index of the first occurrence.
Why do we use lower() method for word searching?
lower() converts text to lowercase to make the search case-insensitive, ensuring 'Python' and 'python' are treated the same.
What does isalpha() method check?
isalpha() returns True if all characters in the string are alphabetic (a-z, A-Z), False otherwise.
How can you count specific characters in a string?
Use a loop to iterate through each character and use conditional statements to count specific characters.