Here is a Python program to find the number of occurrences of a specified word and the total number of words in a text file.
This program takes a filename as input and opens the file in read mode(default mode) using the with
statement. The file is read line by line inside a while
loop and each line is split into a list of words using the split()
method. The length of the list is added to the total number of words. A for
loop iterates through each word of the line and compares it with the search word. If it matches then the search word count variable is incremented.
fname = input("Enter the filename including path: ") search_word = input("Enter word to search: ") total_words = 0 search_word_count = 0 with open(fname) as file: file_line = file.readline() while file_line != '': words = file_line.split() total_words += len(words) for word in words: if (word == search_word): search_word_count = search_word_count + 1 file_line = file.readline() print("There is a total of", total_words, "words in the file.") print("The word", search_word, "occurs", search_word_count, "times.")
A sample output from executing the above program is shown below
Enter the filename including path: ./myfile.txt Enter word to search: blog There is a total of 27 words in the file. The word blog occurs 6 times.