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:
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:
- Copy the code above
- Save it as
text_analyzer.py - Open terminal and run:
python text_analyzer.py - 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
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
- Test the analyzer with different types of text
- Add support for reading text from files
- Implement additional statistics (unique words, etc.)
- Create visualization of word frequency
- Add export functionality for reports
- Implement sentiment analysis
- Build a simple GUI with Tkinter (optional)