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
word_frequency with one parameter, text.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.
counts.get(word, 0) + 1.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"))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.