Skip to contentSkip to navigation

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

Tap any part of the code below, or press Next.1 of 5 explored

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"?

Python
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")
Output
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.

  1. text = "Go go GO stop"
  2. words = text.lower().split()
  3. counts = {}
  4. for w in words:
  5. counts[w] = counts.get(w, 0) + 1
  6. best = max(counts, key=counts.get)
  7. 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 notesOpen

Building the analyser

The brief

The program reads a text file and prints a report: the number of words, how many different words there are, the average word length, the longest word, the number of sentences, and the five most common words with their counts. Words should be counted the same way regardless of capital letters and punctuation, so The, the and the, are one word. If the file does not exist, the program says so instead of crashing.

Plan the steps

Before writing code, list the steps as plain sentences. Each one will become a function:

  1. Read the text from a file.
  2. Split the text into clean, lower-case words.
  3. Count how often each word appears.
  4. Pick the most common words.
  5. Work out the other statistics.
  6. Print the report.

Small functions with clear names can each be tested on their own with a short string, long before the whole program exists. The final program then reads almost like the list above.

Cleaning and splitting

text.split() breaks text on whitespace, but leaves punctuation attached: "end." and "end" would count as different words. A regular expression can pick out just the words instead:

Try it 1: edit me, then Run
import re

def words_in(text):
    return re.findall(r"[a-z']+", text.lower())

print(words_in("It's the END. The end, really!"))
# ["it's", 'the', 'end', 'the', 'end', 'really']
Output
Press Run to see what it prints.

Lower-casing first means the pattern only needs lower-case letters. Including the apostrophe keeps words like it's and don't in one piece. This is a design decision: a different program might choose to split them, or to keep digits. Write such decisions down in a comment so readers know they were deliberate.

Counting

The counting pattern from the dictionaries lesson works perfectly:

Try it 2: edit me, then Run
def count_words(words):
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    return counts
Output
Press Run to see what it prints.

collections.Counter(words) does the same job in one call and adds a most_common method. Either is fine; writing the loop once yourself shows exactly what Counter does for you.

Ranking with a key

To find the most common words, sort the (word, count) pairs by count, highest first. Ties are common in short texts, so break them alphabetically to make the result stable:

Try it 3: edit me, then Run
def top_words(counts, n=5):
    ranked = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
    return ranked[:n]
Output
Press Run to see what it prints.

The key returns a tuple. Tuples compare item by item, so the negative count sorts the highest counts first, and the word decides between equal counts. Negating is a neat trick that works for numbers; for text you would use a second sort instead.

The other statistics

Each statistic is one short expression over the list of words:

Try it 4: edit me, then Run
total = len(words)
unique = len(set(words))
average = sum(len(w) for w in words) / total
longest = max(words, key=len)
Output
Press Run to see what it prints.

Sentences are harder to define. A simple rule, good enough for ordinary prose, counts runs of ., ! or ? with len(re.findall(r"[.!?]+", text)). Abbreviations such as "Dr." will fool it, which is worth mentioning in the report's notes.

Watch out for the empty case: a file with no words would make average divide by zero and max fail on an empty list. Check if not words: first and report an empty document.

Reading the file

Reading is the only step that touches the outside world, so it goes in its own function, which raises or returns cleanly:

Try it 5: edit me, then Run
from pathlib import Path

def load(path):
    try:
        return Path(path).read_text(encoding="utf-8")
    except FileNotFoundError:
        return None
Output
Press Run to see what it prints.

Keeping file access separate means every other function can be tested with plain strings, with no files at all.

Putting it together

The report function calls the others and builds the output. Returning the report as one string, rather than printing inside each helper, makes it easy to print, save to a file or check in a test. At the bottom, a __main__ guard runs the program on a sample file, so the module can also be imported by another program that wants to reuse words_in or top_words.

Ideas to extend it

Once the report works, try ignoring very common words such as "the" and "and" (often called stop words) with a set, comparing two texts to see which words they share, or writing the counts to a CSV file so they can be charted in a spreadsheet.

Syntax

The general shape of the statements in this lesson.

syntax.py
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
Output
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

Intermediate

Write the whole analyser as small functions, save a short sample text to a file, and print its report.

Python
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")))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Each helper does one job and returns a value, so report is a short list of lines built from their results. The empty check guards the average and the maximum. Ties in the top words, such as several words appearing once, are broken alphabetically by the sort key.

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.

Buggy code: run it
text = "Stop. stop, STOP!"
print(len(set(text.lower().split())))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints 3: stop., stop, and stop! look like three different words

Write this instead

import re
text = "Stop. stop, STOP!"
print(len(set(re.findall(r"[a-z']+", text.lower()))))

Why it happens

split only breaks on whitespace, so punctuation stays attached to the words.

In the real world

Where this shows up in software people use every day.

  1. Spotting themes in customer feedback

    Customer experience

    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.

    Python
    import 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}")
    Output
    Press 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?

Both work. Counter is shorter and has most_common, which is handy. Writing the dictionary loop yourself once makes it clear what Counter does.

How do I handle words with accents, like cafe with an accent?

The pattern [a-z']+ skips accented letters. Use [^\W\d_']+ or simply \w+ with re to accept letters from every language, and test it on your own text.

How big a file can this handle?

Reading the whole file is fine for books and reports. For very large logs, read one line at a time and update the counts as you go, so only the counts are kept in memory.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.