Module 12 · Lesson 01
Project: Text Word Statistics
Build a text analyser: read a document from a file, clean and split it into words, count them, rank the most common, and print a tidy report of its statistics.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Clean, count, rank, report
- Count with a dictionary
- Rank with a sort key
- Watch words get counted
The analyser in four parts
Text goes in, a report comes out. Each step is one small function you can test on its own.
Clean
text.lower()and a pattern such as[a-z']+turn text into a tidy list of words.Count
A dictionary, or a
Counter, keeps how many times each word appears.Rank
Sort the counts so the most common words come first, with ties in A to Z order.
Report
Total words, unique words, the average length and the longest word.
Word counts everywhere
Counting words is the first step of many real text tools.
- Search enginesWords that appear often on a page hint at what the page is about.
- Word cloudsThe most common words are drawn the biggest.
- Essay toolsWord counters and reading-time estimates count words just like this.
- Lyrics statsFind the word a songwriter uses most.
Counting one word
This line is the heart of the counter. Tap each part to see its job.
Part 1 of 5
dictionary:Maps each word to how many times it has been seen so far.
Build the analyser in five steps
Build the project one step at a time. Each example runs on its own: change it, then press Run.
Example 1 of 61. Clean
Lower-case first, then let a pattern pick out the words.
Your turn: Remove .lower() and run. What happens to "The" and "CAT"?
import re text = "The cat sat. The CAT ran! It's the cat's mat." words = re.findall(r"[a-z']+", text.lower()) print(words) print(len(words), "words")
Press Run to see what it prints.Watch words get counted
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- text = "Go go GO stop"
- words = text.lower().split()
- counts = {}
- for w in words:
- counts[w] = counts.get(w, 0) + 1
- best = max(counts, key=counts.get)
- print(best, counts[best])
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Counting words with split():
line = "rain rain go away"
print(len(line.split()))0 of 6 answered
Common analyser misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
re.findall(r"[a-z']+", text.lower()) # clean words counts[w] = counts.get(w, 0) + 1 # count sorted(counts.items(), key=lambda p: (-p[1], p[0]))[:5] # top 5, ties by word len(set(words)) # unique words max(words, key=len) # longest Path(p).read_text(encoding="utf-8") # read the file
Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
The complete report
Write the whole analyser as small functions, save a short sample text to a file, and print its report.
import re
from pathlib import Path
def words_in(text):
return re.findall(r"[a-z']+", text.lower())
def count_words(words):
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts
def top_words(counts, n=5):
return sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))[:n]
def report(text):
words = words_in(text)
if not words:
return "Empty document"
counts = count_words(words)
lines = [
f"Words: {len(words)}",
f"Unique: {len(counts)}",
f"Average length: {sum(len(w) for w in words) / len(words):.2f}",
f"Longest: {max(words, key=len)}",
f"Sentences: {len(re.findall(r'[.!?]+', text))}",
"Top words:",
]
lines += [f" {word}: {count}" for word, count in top_words(counts, 3)]
return "\n".join(lines)
Path("sample.txt").write_text(
"The cat sat. The cat ran! Did the dog see the cat? It's a busy day.",
encoding="utf-8",
)
print(report(Path("sample.txt").read_text(encoding="utf-8")))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Counting punctuation as part of words
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
text = "Stop. stop, STOP!" print(len(set(text.lower().split())))
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Customer experience
Spotting themes in customer feedback
A support team receives hundreds of short comments a week. Counting the most frequent meaningful words in the complaints shows which problems to look at first.
Why Python fits
One comprehension with two for clauses turns every comment into clean words and drops the stop words. Counter does the counting, and the same tie-breaking key as the main project ranks the themes. Late delivery and damaged boxes stand out at once.
Pythonimport re from collections import Counter STOP = {"the", "a", "is", "was", "my", "and", "to", "it", "too", "i", "of"} comments = [ "Delivery was late and the box was damaged", "Late delivery again, my order is late", "The app crashed when I paid", "Box damaged, item fine", "Delivery driver was lovely but late", ] words = [w for c in comments for w in re.findall(r"[a-z]+", c.lower()) if w not in STOP] for word, count in sorted(Counter(words).items(), key=lambda p: (-p[1], p[0]))[:4]: print(f"{word:<10}{count}")OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Should I use Counter or a dictionary?
How do I handle words with accents, like cafe with an accent?
How big a file can this handle?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 6 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.