Skip to content
Python project #06Beginner

Text Analyzer

Count characters, words, sentences and paragraphs, estimate reading time and readability, and chart word frequencies and lengths.

Estimated time
~2 hours to build
Files
4 files · 225 lines
Technologies
Python 3, re, collections.Counter

Introduction

Writers, students and editors all want quick facts about a piece of text. This tool reads any text from standard input and reports statistics, a Flesch readability score, the most frequent meaningful words and a word-length histogram.

Problem statement

Read text from standard input. Report the number of characters and letters, words and unique words, sentences and paragraphs, average word and sentence length, reading time at 200 words per minute and a Flesch reading-ease score with a label. List the five most frequent words excluding common stop words, the three longest words, and a histogram of word lengths.

Objectives

  • Use regular expressions to split text
  • Count with collections.Counter
  • Implement a simple syllable heuristic and the Flesch formula
  • Print aligned tables and text bar charts

Features

  • Character, word, sentence and paragraph counts
  • Reading time and Flesch readability label
  • Top words without stop words
  • Longest words
  • Word-length histogram

Concepts demonstrated

  • Regular expressions
  • Frequency counting
  • Heuristics
  • Text formatting

System architecture

analyse does all the computation and returns a dictionary of results: it finds words with a regular expression, splits sentences on . ! ?, splits paragraphs on blank lines and counts syllables with count_syllables. readability_label turns the Flesch score into words. main reads standard input and prints the sections.

Folder structure

TextProject tree
text-analyzer/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

87 lines
Pythonmain.py
"""Text Analyzer: statistics, word frequencies and readability for any text.
Paste or pipe text into standard input: python main.py < essay.txt
"""
import re
import sys
from collections import Counter
STOP_WORDS = {
"a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "from", "has", "have", "he", "her", "his", "i",
"in", "is", "it", "its", "of", "on", "or", "she", "so", "that", "the", "their", "them", "they", "this", "to",
"was", "we", "were", "will", "with", "you", "your", "can", "not", "do", "does", "than", "then", "there", "these",
}
WORDS_PER_MINUTE = 200
def count_syllables(word: str) -> int:
"""A simple heuristic: count vowel groups, ignore a silent final 'e', at least one per word."""
groups = re.findall(r"[aeiouy]+", word.lower())
count = len(groups)
if word.lower().endswith("e") and count > 1:
count -= 1
return max(count, 1)
def analyse(text: str) -> dict:
words = re.findall(r"[A-Za-z']+", text)
sentences = [s for s in re.split(r"[.!?]+", text) if s.strip()]
paragraphs = [p for p in re.split(r"\n\s*\n", text) if p.strip()]
lowered = [w.lower().strip("'") for w in words]
syllables = sum(count_syllables(w) for w in words)
n_words, n_sentences = len(words), max(len(sentences), 1)
flesch = 206.835 - 1.015 * (n_words / n_sentences) - 84.6 * (syllables / max(n_words, 1))
return {
"characters": len(text),
"letters": sum(c.isalpha() for c in text),
"words": n_words,
"unique": len(set(lowered)),
"sentences": len(sentences),
"paragraphs": len(paragraphs),
"average_word": sum(len(w) for w in words) / max(n_words, 1),
"average_sentence": n_words / n_sentences,
"flesch": flesch,
"minutes": n_words / WORDS_PER_MINUTE,
"top": Counter(w for w in lowered if w not in STOP_WORDS).most_common(5),
"longest": sorted(set(lowered), key=lambda w: (-len(w), w))[:3],
"lengths": Counter(min(len(w), 10) for w in words),
}
def readability_label(score: float) -> str:
for limit, label in [(80, "very easy"), (60, "easy / plain English"), (50, "fairly difficult"), (30, "difficult")]:
if score >= limit:
return label
return "very difficult"
def main() -> None:
text = sys.stdin.read()
if not text.strip():
print("No text given. Usage: python main.py < file.txt")
return
r = analyse(text)
print("TEXT STATISTICS")
print(f" Characters {r['characters']:>6} (letters {r['letters']})")
print(f" Words {r['words']:>6} (unique {r['unique']})")
print(f" Sentences {r['sentences']:>6}")
print(f" Paragraphs {r['paragraphs']:>6}")
print(f" Avg word {r['average_word']:>6.2f} letters")
print(f" Avg sentence {r['average_sentence']:>6.1f} words")
seconds = round(r["minutes"] * 60)
print(f" Reading time {seconds // 60} min {seconds % 60:02d} s at {WORDS_PER_MINUTE} wpm")
print(f" Readability {r['flesch']:>6.1f} ({readability_label(r['flesch'])})")
print("TOP WORDS (common words excluded)")
for word, count in r["top"]:
print(f" {word:<14}{count:>3} {'#' * count}")
print("LONGEST WORDS")
print(" " + ", ".join(r["longest"]))
print("WORD LENGTHS")
for length in sorted(r["lengths"]):
label = f"{length}+" if length == 10 else str(length)
print(f" {label:>3} letters {r['lengths'][length]:>3} {'*' * r['lengths'][length]}")
if __name__ == "__main__":
main()

What each file does

main.py
The whole program: data classes, validation, the command loop and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
TEXT STATISTICS
Characters 349 (letters 280)
Words 55 (unique 39)
Sentences 7
Paragraphs 3
Avg word 5.11 letters
Avg sentence 7.9 words
Reading time 0 min 16 s at 200 wpm
Readability 69.7 (easy / plain English)
TOP WORDS (common words excluded)
python 3 ###
programming 3 ###
code 2 ##
easy 2 ##
programs 2 ##
LONGEST WORDS
programming, wonderful, automate
WORD LENGTHS
1 letters 2 **
2 letters 6 ******
3 letters 4 ****
4 letters 16 ****************
5 letters 8 ********
6 letters 5 *****
7 letters 1 *
8 letters 9 *********
9 letters 1 *
10+ letters 3 ***
Input
Python is a programming language that lets you work quickly. Python code is easy to read, and readable code is easy to maintain!

Many students learn Python first. They write small programs, then bigger programs, and soon they automate boring tasks. Isn't that wonderful?

Programming is a skill. Like any skill, programming improves with practice.

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • The sample has 55 words in 7 sentences and 3 paragraphs.
  • 'python' and 'programming' are the top words with 3 uses each.
  • The readability score is about 70, labelled easy / plain English.

Common errors

Words such as don't are split in two

Include the apostrophe in the word pattern: [A-Za-z']+.

Empty input crashes with ZeroDivisionError

Check for blank text first and use max(count, 1) when dividing.

Possible improvements

  • Read files given as command-line arguments
  • Add a list of the most common two-word phrases
  • Detect the language with a tiny stop-word list per language

Additional challenges

  1. 1Highlight sentences longer than 25 words.
  2. 2Compute the Gunning fog index as well.
  3. 3Compare two texts and report words that appear in only one.

Built and tested it yourself? Mark it to update your dashboard.