HomeComputer SciencePracticalClass 12Count Occurrences

Class 12 Programs

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

  1. Start
  2. Open the text file in read mode
  3. Read the entire content of the file
  4. Count occurrences of a specific word (case-insensitive)
  5. Initialize counters for vowels and consonants
  6. Iterate through each character in the file content
  7. Check if character is a vowel or consonant
  8. Increment respective counters
  9. Display the results
  10. 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

  1. 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.

  2. 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.

  3. 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.

  4. What does isalpha() method check?

    isalpha() returns True if all characters in the string are alphabetic (a-z, A-Z), False otherwise.

  5. 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.