Practice: Word Count

Practice: Word Count

This exercise combines lower, split, a loop, and a counter.

Exercise

  1. Define a function named count_word with two parameters: text and word.
  2. It returns how many times word appears in text as a whole word, ignoring case.

count_word("The cat saw the other cat", "cat") returns 2. count_word("The cat", "THE") returns 1.

Whole word means "cat" does not match inside "concatenate" — splitting the text into words before comparing handles this.

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

Hints

  • Lowercase both text and word before comparing.
  • Split the text into a word list, then count matches with an accumulator.

Tests

import unittest


class TestCountWord(unittest.TestCase):
    def test_two_matches(self):
        self.assertEqual(count_word("The cat saw the other cat", "cat"), 2)

    def test_case_is_ignored(self):
        self.assertEqual(count_word("The cat", "THE"), 1)

    def test_substrings_do_not_count(self):
        self.assertEqual(count_word("concatenate the strings", "cat"), 0)

    def test_no_match_gives_zero(self):
        self.assertEqual(count_word("nothing here", "cat"), 0)
def count_word(text, word):
    target = word.lower()
    count = 0
    for candidate in text.lower().split():
        if candidate == target:
            count += 1
    return count


print(count_word("The cat saw the other cat", "cat"))
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.