Count a word in a file

EasyFile Handling Programs · 10 of 38

Write a Python program to count how many times a word occurs in a file.

Advertisement
Output
4

Approach

  1. Lower-case the words and count matches.

Solution

Python
with open("story.txt", "w") as f:    f.write("Test early. Test often.\nA good test is a fast test.\n") with open("story.txt") as f:    words = [w.strip(".,").lower() for w in f.read().split()]print(words.count("test"))
Output
4

Line by line

Line 5

Stripping punctuation and lower-casing makes “Test”, “test.” and “test” match.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs