BeginnerStrings & dicts

Count words

Task

Write word_count(text) that returns a dict of how often each word appears. Split on whitespace, strip the punctuation . , ! ? ; : from both ends of each word, ignore case, and skip anything that is empty after stripping.

Python 3.14 running in your browser (Pyodide). Standard library only. print() output is shown below the results.

Tests
CallExpected
word_count('The cat. the CAT!'){'the': 2, 'cat': 2}
word_count('Data, data; DATA?'){'data': 3}
word_count('a b\n a'){'a': 2, 'b': 1}
word_count(''){}
word_count('... !!! ok'){'ok': 1}
Show solution
Python
def word_count(text):
    counts = {}
    for raw in text.split():
        word = raw.strip('.,!?;:').lower()
        if word:
            counts[word] = counts.get(word, 0) + 1
    return counts

split() without arguments handles repeated spaces and newlines; split(" ") produces empty strings. collections.Counter is the idiomatic counter, but only after cleaning the words.

Revise in the Python guide, or test yourself with the Python practice sets.