Practice: Word Frequency

Practice: Word Frequency

This exercise combines split, lower, a loop, and building a dictionary — counting how often each word occurs in a text.

The counting pattern for dictionaries: when the key is new, start it at zero; then add one.

counts = {}
for word in words:
    if word not in counts:
        counts[word] = 0
    counts[word] += 1

Exercise

  1. Define a function named word_frequency with one parameter, text.
  2. It returns a dictionary mapping each word (lowercased) to how many times it appears.

word_frequency("the cat saw the dog") returns {"the": 2, "cat": 1, "saw": 1, "dog": 1}.

Run your code to see the output, then press Submit.

Hints

  • Lowercase and split the text first.
  • Use the counting pattern shown above, or counts.get(word, 0) + 1.

Tests

import unittest


class TestWordFrequency(unittest.TestCase):
    def test_simple_sentence(self):
        self.assertEqual(
            word_frequency("the cat saw the dog"),
            {"the": 2, "cat": 1, "saw": 1, "dog": 1},
        )

    def test_case_is_ignored(self):
        self.assertEqual(word_frequency("The the THE"), {"the": 3})

    def test_empty_text_gives_empty_dictionary(self):
        self.assertEqual(word_frequency(""), {})
def word_frequency(text):
    counts = {}
    for word in text.lower().split():
        if word not in counts:
            counts[word] = 0
        counts[word] += 1
    return counts


print(word_frequency("the cat saw the dog"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.