← Intro to programming with Python

Mini project: word frequency counter

Find the most common words in a piece of text.

Start this lesson

Search engines and spam filters start by counting words. The plan: tidy the text (lowercase, take out punctuation), split it into words, count each word with a dictionary, then report the results. Each step is something you already know; the project is putting them in a row.

text = "The cat sat. The cat ran!"
for mark in ".,!?":
    text = text.replace(mark, "")
words = text.lower().split()
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(counts)   # {'the': 2, 'cat': 2, 'sat': 1, 'ran': 1}

Removing punctuation first means "ran!" and "ran" are counted as the same word.

Common mistake: forgetting lower(). Then "The" and "the" are counted as two different words.