Practice: Word Count for a File

Practice: Word Count for a File

This exercise combines reading a file with split and a counter — the file version of the word counting you did in the strings section.

Exercise

  1. Define a function named word_count with one parameter, path.
  2. It returns the total number of words in the file. Words are whatever split produces — chunks separated by any whitespace, including newlines.

For a file containing the quick brown fox on one line and jumps on the next, the result is 5.

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

Hints

  • read the whole file into one string; split handles newlines like spaces.
  • The body fits in three lines.

Tests

import unittest


class TestWordCount(unittest.TestCase):
    def test_words_across_two_lines(self):
        with open("test_story.txt", "w") as file:
            file.write("the quick brown fox\njumps\n")
        self.assertEqual(word_count("test_story.txt"), 5)

    def test_empty_file_has_zero_words(self):
        with open("test_empty_story.txt", "w") as file:
            file.write("")
        self.assertEqual(word_count("test_empty_story.txt"), 0)

    def test_multiple_spaces_between_words(self):
        with open("test_spaced.txt", "w") as file:
            file.write("a   b\n")
        self.assertEqual(word_count("test_spaced.txt"), 2)
def word_count(path):
    with open(path) as file:
        return len(file.read().split())


with open("story.txt", "w") as file:
    file.write("the quick brown fox\njumps\n")

print(word_count("story.txt"))
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.