Learn Python · lesson 32 of 60 · about 8 minutes
Project: Word Counter
Count how often each word appears in Sam's diary line using a dictionary.
What you'll learn
- Split text into words
- Count with a dictionary
- Report the most common word
Sam's diary
At the end of the day Sam types one line for a diary, like Swim was fun. Swim again tomorrow!. The assistant counts the words in it: how many different words there are, and which one came up most. Capitals and full stops shouldn't make Swim and swim. look like different words, so the line is lower-cased and each word has its punctuation stripped off before it's counted.
The plan
1. Make the text lowercase and split() it into a list of words
2. For each word, add 1 to its count in a dictionary
3. Find the word with the biggest count
split() with no arguments breaks text on spaces. counts.get(word, 0) + 1 handles words you haven't seen yet.
Word counter
text = "the cat sat on the mat the end"
counts = {}
for word in text.lower().split():
counts[word] = counts.get(word, 0) + 1
print(counts["the"])
best = max(counts, key=counts.get)
print(f"Most common: {best} ({counts[best]})")Output
3
Most common: the (3)Tip
max(counts, key=counts.get) loops over the keys and picks the one whose value is biggest. key= tells max what to compare.
Tip
strip(".,!?") takes those characters off both ends of a word, wherever they are in the list you give it, so "fun." becomes "fun" and "tomorrow!" becomes "tomorrow".
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.