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.
Walk through a concrete input
For "Python python code", lower() produces "python python code" and split() produces three tokens. Starting with {}, the first token creates python: 1; the second updates python to 2; the third creates code: 1. The final result is {"python": 2, "code": 1}. The count sum is three, equal to the number of tokens, which is a useful independent check.
Now try "code, code". The expected result is {"code,": 1, "code": 1}, because the comma is retained. Removing punctuation would change the contract. Decide whether you want that before changing the implementation; filenames, contractions and programming symbols need different tokenization rules.
Build and explain the solution
Inside frequencies, initialize counts = {}. Then write for word in text.lower().split(): and, indented inside that loop, counts[word] = counts.get(word, 0) + 1. Return counts after the loop, at the same indentation as the loop statement. get supplies zero only for a new word; subsequent occurrences use the accumulated value.
Returning inside the loop stops after the first word. Using counts[word] += 1 without initializing a new key raises KeyError. Using split(" ") instead of split() preserves empty tokens for repeated spaces and does not handle newlines the same way. Test empty text, mixed case and a multiline string separately to reveal these mistakes.
Processing n tokens takes O(n) expected dictionary operations and stores k distinct keys. This version also allocates the normalized string and token list. For very large files, process lines incrementally with an explicit encoding and keep one accumulator for the file. Do not reuse that accumulator for an unrelated document.
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.