Mini-Project: Word Counter
dict.get(), and sorted by value instead of by key.Before you start
#What you'll build
A program that takes a chunk of text and returns the word frequencies, sorted from most common to least common.
Sample interaction
Text: the cat sat on the mat the cat slept
the: 3
cat: 2
sat: 1
on: 1
mat: 1
slept: 1
#What you'll learn
After this lesson, you will be able to:
- Split a string into words with .split()
- Build a counter in a dict with the counts[word] = counts.get(word, 0) + 1 pattern
- Sort a dict by its values using sorted() and a key lambda
#Step 1: Split text into words
.split() with no arguments breaks a string into a list of "tokens", separating on any whitespace and dropping empty strings.text = "the cat sat on the mat"
words = text.split()
print(words)
# ['the', 'cat', 'sat', 'on', 'the', 'mat']That's all you need to start counting — a list of words.
What does " one two three ".split() return? (split with NO argument)
What does `' hello world '.split()` return?
#Step 2: Tally with a dict
Loop over the words. For each word, check if it's already a key in the dict — if yes, add one; if no, start at one.
text = "the cat sat on the mat the cat slept"
words = text.split()
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(counts)
# {'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1, 'slept': 1}That works, but there's a slicker way — next step.
#Step 3: Tally with dict.get
counts.get(word, 0) returns the current count, or 0 if the word hasn't been seen yet. That eliminates the if/else.counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)collections.Counter in the lesson on the collections module. This project builds the counter by hand so you can see exactly what Counter does for you; dict.get(key, 0) + 1 is what every Python coder starts with.)What happens? counts = {} counts["cat"] += 1
What does `counts.get('xyz', 0)` return if 'xyz' is not in counts?
#Step 4: Sort by count, high to low
sorted() with a key lambda and reverse=True.counts = {'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1, 'slept': 1}
ranked = sorted(counts.items(), key=lambda kv: kv[1], reverse=True)
for word, count in ranked:
print(f"{word}: {count}")
# the: 3
# cat: 2
# sat: 1
# ...counts.items() returns (key, value) tuples. key=lambda kv: kv[1] tells sorted to sort by the SECOND element of each tuple — the count. reverse=True flips it to descending.What is the FIRST element after sorting? items = [("apple", 3), ("banana", 1), ("cherry", 2)] sorted_items = sorted(items, key=lambda kv: kv[1])
key function tells sorted what to compare by — here kv[1] is the second element of each tuple (the count). So Python compares 3, 1, 2, and orders ASCENDING by default: 1, 2, 3. ('banana', 1) comes first. Without the key, sorted would compare tuples lexicographically (by first element first) and order alphabetically: apple, banana, cherry. The key= parameter is the unlock for sorting by any computed property — by length (key=len), by score (key=lambda x: x.score), or by anything else.#Step 5: Wrap it as a function
def word_counts(text):
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
return sorted(counts.items(), key=lambda kv: kv[1], reverse=True)
for word, n in word_counts("the cat sat on the mat the cat slept"):
print(f"{word}: {n}")Five-line function. Works on any string — a sentence, a paragraph, the contents of a file (once you learn file I/O).
#Now build it yourself
Case-insensitive word counter that ignores punctuation
Write a function `word_counts(text)` that returns a list of (word, count) tuples sorted by count descending. Make it case-insensitive ('The' and 'the' should count as the same word) and strip punctuation ('cat,' and 'cat' should count as the same word). Use only the standard library.
the: 3
cat: 3
sat: 1
slept: 1
on: 1
mat: 1
a: 1
happy: 1#Now make it your own
Try one of these variations:
- Top N only. Add a
top=10parameter so the function returns only the 10 most common words. Use list slicing on the sorted result. - Stopword filter. Skip common words like "the", "a", "is" using a
STOPWORDS = {"the", "a", "an", "is", ...}set. Only count words NOT in stopwords. - Read from a file — once you've done the file I/O lesson, point the counter at a real text file (e.g., a book from Project Gutenberg) and see what its top 20 words are.
#What's next
word_counts becomes one piece of a larger text-processing pipeline.