Project: a word report
This lesson puts the course together. A word report reads text, cleans it into words, counts them and lists the most common ones. Split the job into small functions so each step can be tested alone.
import string
from collections import Counter
print(string.punctuation)
print("'Hi!'".strip(string.punctuation))
print("don't".strip(string.punctuation))
print(repr("...".strip(string.punctuation)))
words = ["the", "cat", "the"]
print(Counter(words).most_common(1))The plan
clean_wordslower-cases the text, splits it on whitespace, strips punctuation from both ends of each piece, and drops pieces that end up empty. Stripping only the ends keeps words likedon'twhole.Counter(words).most_common(n)finds the top words. Equal counts keep the order in which the words first appeared.- Formatting comes last, in its own function, so the counting can be checked without reading printed text.
Test each function on a tiny input you can count by hand before trusting it with a long text.
Your task
Write clean_words(text) returning the lower-case words of text, with punctuation stripped from both ends of each and empty results dropped. Write report(text, n) returning the n most common words as lines like "cat: 2" joined with newlines, or "no words" when there are none.
The explanation opens here once every check passes.