================================================================================
  Question 19: Read and Analyze Text File
================================================================================

FULL QUESTION:
Task:
1. Read a text file (sample.txt).
2. Count and display:
   - Total number of lines.
   - Total number of words.
   - Total number of characters.
3. Find the frequency of each word using collections.Counter.
4. Display the top 5 most frequently occurring words.
5. Handle exceptions such as FileNotFoundError and PermissionError.

SHORT QUESTION:
Text file analysis program reporting line, word, character counts, and top 5 word frequencies with error handling.

================================================================================
README & SETUP INSTRUCTIONS:
================================================================================
# Question 19: Read and Analyze Text File

- Prerequisites: Python 3.x (Standard library collections module).
- Setup: Reads 'sample.txt'. If missing, the script automatically creates a sample file.
- How to Run: python question_19.py
- Expected Behavior: Prints total line count, word count, character count, and top 5 most frequent words.

================================================================================
SOURCE CODE FILES:
================================================================================

1. question_19.py
--------------------------------------------------------------------------------
from collections import Counter

filename = "sample.txt"

try:
    with open(filename, "r") as file:
        lines = file.readlines()

    line_count = len(lines)

    full_text = "".join(lines)
    char_count = len(full_text)

    words = full_text.lower().split()
    word_count = len(words)

    word_frequencies = Counter(words)
    top_5_words = word_frequencies.most_common(5)

    print(f"--- File Analysis for '{filename}' ---")
    print(f"Total Lines      : {line_count}")
    print(f"Total Words      : {word_count}")
    print(f"Total Characters : {char_count}\n")

    print("--- Top 5 Most Frequent Words ---")
    for word, count in top_5_words:
        print(f"'{word}': {count} times")

except FileNotFoundError:
    print(f"Error: The file '{filename}' does not exist. Please check the file path.")
except PermissionError:
    print(f"Error: You do not have the required permissions to read '{filename}'.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
--------------------------------------------------------------------------------
