๐Ÿ“

    Text Analyzer

    Intermediate Project

    Analyze words, sentences, and keyword frequency using string methods, collections, and decorators.

    Project Overview

    Goal: Analyze text files and generate statistics.

    Concepts: String methods, collections.Counter, decorators for timing.

    Key Features:

    • โ€ข Word and character count
    • โ€ข Most common words
    • โ€ข Reading level analysis
    • โ€ข Find and replace functionality
    • โ€ข Generate summary reports

    Technologies & Concepts:

    String MethodsRegular ExpressionsCollectionsDecoratorsFile I/O

    Starter Code

    ๐Ÿ’ก Note: Interactive Code

    This is a command-line app that uses input() for user interaction. The browser demo below shows a simplified version. For the full interactive experience, copy the code below and run it in your local Python environment (IDLE, VS Code, or terminal).Jump to the Browser Demo.

    Here's a functional starting version of your app. Copy it to your local Python editor and run it.

    import re
    from collections import Counter
    import time
    
    # Decorator to measure execution time
    def timer(func):
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            print(f"\nโฑ Execution time: {time.time() - start:.3f}s")
            return result
        return wrapper
    
    class TextAnalyzer:
        def __init__(self, text=""):
            self.text = text
    
        def load_file(self, filename):
            try:
                with open(filename, "r", encoding="utf-8") as f:
                    self.text = f.read()
                print(f"๐Ÿ“‚ Loaded file: {filename}")
            except FileNotFoundError:
                print("โŒ File not found.")
    
        @timer
        def analyze(self):
            words = re.findall(r"\b\w+\b", self.text.lower())
            sentences = re.split(r"[.!?]+", self.text)
            char_count = len(self.text)
            word_count = len(words)
            sentence_count = len([s for s in sentences if s.strip()])
            unique_words = len(set(words))
            freq = Counter(words).most_common(10)
    
            print(f"\n๐Ÿ“Š Text Statistics:")
            print(f"Characters: {char_count}")
            print(f"Words: {word_count}")
            print(f"Unique Words: {unique_words}")
            print(f"Sentences: {sentence_count}")
            print("\n๐Ÿ”  Most Common Words:")
            for w, c in freq:
                print(f"{w}: {c}")
    
        def find_replace(self, old, new):
            self.text = self.text.replace(old, new)
            print(f"โœ… Replaced '{old}' with '{new}'")
    
        def save_report(self, filename="report.txt"):
            with open(filename, "w", encoding="utf-8") as f:
                f.write(self.text)
            print(f"๐Ÿ’พ Report saved to {filename}")
    
    # Demo Menu
    if __name__ == "__main__":
        analyzer = TextAnalyzer()
        while True:
            print("\n--- TEXT ANALYZER ---")
            print("1. Load Text File")
            print("2. Analyze Text")
            print("3. Find & Replace")
            print("4. Save Report")
            print("5. Exit")
            choice = input("Choose option: ")
    
            if choice == "1":
                filename = input("Enter filename: ")
                analyzer.load_file(filename)
            elif choice == "2":
                analyzer.analyze()
            elif choice == "3":
                old = input("Find: ")
                new = input("Replace with: ")
                analyzer.find_replace(old, new)
            elif choice == "4":
                analyzer.save_report()
            elif choice == "5":
                print("๐Ÿ‘‹ Exiting...")
                break
            else:
                print("โŒ Invalid choice.")

    ๐Ÿš€ How to Run Locally:

    1. Copy the code above
    2. Save it as text_analyzer.py
    3. Open terminal and run: python text_analyzer.py
    4. Follow the interactive menu to analyze text

    ๐ŸŽฎ Browser Demo (Simplified Version)

    This browser version demonstrates the core logic without user input. Click Run to see it work!

    Text Analyzer Demo

    Try it Yourself ยป
    Python
    from collections import Counter
    import re
    import time
    
    def timer(func):
        """Decorator to measure function execution time"""
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            elapsed = time.time() - start
            print(f"\nโฑ๏ธ  {func.__name__} took {elapsed:.4f}s")
            return result
        return wrapper
    
    class TextAnalyzer:
        def __init__(self, text):
            self.text = text
            self.words = re.findall(r'\b\w+\b', text.lower())
    ...

    Enhancement Ideas ๐Ÿš€

    1. File Upload Support

    Allow users to upload text files and automatically analyze them.

    2. Sentiment Analysis

    Use the textblob library to determine if text is positive, negative, or neutral.

    3. Reading Level Calculator

    Implement the Flesch-Kincaid readability test to calculate the reading level.

    4. Word Cloud Generation

    Use matplotlib and wordcloud to create visual word clouds.

    5. Compare Multiple Texts

    Add functionality to compare two texts and find similarities/differences.

    Next Steps

    1. Test the analyzer with different types of text
    2. Add support for reading text from files
    3. Implement additional statistics (unique words, etc.)
    4. Create visualization of word frequency
    5. Add export functionality for reports
    6. Implement sentiment analysis
    7. Build a simple GUI with Tkinter (optional)
    Back to Projects

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service