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 – count()
Following is the syntax of count() function.
n = String.count(word)
word is the string, and
count() returns the number of occurrences of
word in this String.
Example 1: Count how many times a word occurred in given Text File
In this example, we will consider the following text file, and count the number of occurrences of “python” word.
Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.
#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)
Number of occurrences of the word : 2
In this tutorial of Python Examples, we learned how to count number of occurrences of a word in a given string.