──────────────────────────────────────

23. The Message Sorting Desk · Count What Comes Up Most

Tokenise text and count repeated words with Counter.

Lesson files · lessons/text-automation/word-frequency

Before you start
- Read a regular expression with a character range.
- Use a dictionary to look up counts and print keys in order.

By the end
- Extract and count a–z tokens after lowercasing, then print the counts alphabetically.
- Explain the empty output for a line made only of punctuation.

Where you can use it
Count repeated words in a short set of suggestions to decide which terms to review first.

A token is one piece of text you choose to count. After lowercasing the line, re.findall with [a-z]+ collects each run of one or more letters from a to z. Counter gives each token a count that you can look up by word. Sort the keys to print the counts in alphabetical order.

Predict
Why do Rain and rain count as the same word?
- The text is lowercased before matching.
- Counter always ignores case.

Worked example (example.py)

import re
from collections import Counter
words = re.findall(r"[a-z]+", "Rain, rain! Sun".lower())
print(Counter(words)["rain"])


Example result
2

Read one line. Count all tokens made of a–z after lowercasing. Print word: count in alphabetical order.

Starter program (starter.py)

import re
from collections import Counter
words = re.findall(r"[a-z]+", "Rain, rain! Sun".lower())
print(Counter(words)["rain"])


Hint
Use re.findall, Counter(words), then iterate over sorted(counts).

Case 1. Try the sample
Input
Rain, rain! Sun
Expected output
rain: 2
sun: 1

Case 2. Punctuation only
Input
!!!
Expected output
(No output.)

Stretch
Change the tokenizer to recognise Unicode letters and see what happens for café.

Reflect
What kind of word is missed by the simple a–z pattern?

Check your prediction
The text is lowercased before matching. Counter compares the exact tokens it receives. The earlier lower() did the case conversion.
