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
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
Complete source code
main.py
What each file does
- main.py
- The whole program: data classes, validation, the command loop and the report.
How to run it
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
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.txtand compare withtests/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
- 1Highlight sentences longer than 25 words.
- 2Compute the Gunning fog index as well.
- 3Compare two texts and report words that appear in only one.
Built and tested it yourself? Mark it to update your dashboard.