Python Practice / Exercise

Count words with Python

Normalize text and build a frequency table using real Python in an isolated browser runtime.

You will learn to

  • Write a dictionary accumulator
  • Normalize whitespace and case
  • Compare a standard-library alternative

Before you start

Python loops and dictionaries

Choose a normalization policy

We lowercase text and split on whitespace. That treats PYTHON and python as one token, but keeps punctuation attached. It is a deliberate small contract, not a universal natural-language tokenizer. State that limitation before applying the code to real documents.

Count without hidden state

Create a fresh dictionary on each call. Read each word’s old count with a default of zero and add one. A global dictionary would accidentally carry counts between exercises. Empty text should produce an empty dictionary, not a dictionary containing an empty string.

Explore the standard library

After your implementation passes, try from collections import Counter and return dict(Counter(text.lower().split())). Counter is part of Python, so no external package is required. Compare readability and behavior. This tested library example does not imply support for arbitrary pip packages.

Try it yourself

def frequencies(text):
    counts = {}
    # Add one count for every normalized word.
    return counts

print(frequencies("Python python code"))

Enable JavaScript for this interactive activity. You can read all lesson explanations above without it.

Continue exploring