Python - Count number of occurrences of a word in Text File


Count occurrences of a word in text file

To count the number of occurrences of a specific word in a text file, read the content of text file to a string and use String.count() function with the word passed as argument to the count() function.

Syntax of count()

Following is the syntax of count() function.

n = String.count(word)

where word is the string, and count() returns the number of occurrences of word in this String.

Examples

1. Count how many times the word "python" occurred in given Text File

In this example, we will consider the following text file, and count the number of occurrences of "python" word.

Text File

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.

Python Program

#get file object reference to the file
file = open("C:\workspace\python\data.txt", "r")

#read content of file to string
data = file.read()

#get number of occurrences of the substring in the string
occurrences = data.count("python")

print('Number of occurrences of the word :', occurrences)

Output

Number of occurrences of the word : 2

Summary

In this tutorial of Python Examples, we learned how to count number of occurrences of a word in a given string.