Beginner Python Exercises

Count Word Frequency in Python

Word-frequency counting is a common text-processing task used in search, reporting, and natural-language analysis.

What is Count Word Frequency?

Word-frequency counting is a common text-processing task used in search, reporting, and natural-language analysis.

Count repeated words in Python with collections.Counter.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

Example code

Run code →
main.py
from collections import Counter
import re

text = "Python is clear. Python is practical."
words = re.findall(r"[a-z]+", text.lower())

print(Counter(words))

Expected output

Counter({'python': 2, 'is': 2, 'clear': 1, 'practical': 1})

How it works

Lowercasing and removing punctuation normalizes equivalent words. Counter then calculates the number of occurrences of every token.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →