This exercise combines reading a file with split and a counter — the file version of the word counting you did in the strings section.
word_count with one parameter, path.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.
read the whole file into one string; split handles newlines like spaces.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"))
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.