This Python program counts the occurrences of a specified word in a text file
Problem Statement
You are tasked with creating a Python program that reads the content of a given text file and counts the occurrences of a specific target word. Your program should provide the user with a way to input the target word, and it should then display the count of how many times that word appears in the text file, regardless of its capitalization.
Python Program to Count the Occurrences of a Word in a Text File
def count_word_occurrences(file_path, target_word):
try:
with open(file_path, 'r') as file:
content = file.read()
word_count = content.lower().count(target_word.lower())
return word_count
except FileNotFoundError:
print("File not found.")
return 0
file_path = 'path/to/your/text/file.txt' # Update this with the actual file path
target_word = input("Enter the word to count: ")
occurrences = count_word_occurrences(file_path, target_word)
print(f"The word '{target_word}' appears {occurrences} times in the file.")
How it Works
1. Defining the Function count_word_occurrences
This function takes two parameters: file_path (the path to the text file) and target_word (the word to be counted). Inside the function:
- The
tryblock attempts to open the specified file in read mode using awithstatement. This is a context manager that ensures the file is properly closed after its suite finishes executing. - If the file is successfully opened, its content is read using the
read()method, and the lowercase version of the content is stored in thecontentvariable. - The
count()method is used to count the occurrences of the lowercasetarget_wordwithin the lowercasecontent. - The function returns the count of occurrences.
If a FileNotFoundError occurs (i.e., the specified file doesn’t exist), the except block prints an error message and returns 0.
2. Getting User Input and Counting Occurrences
- The
file_pathvariable is set to the path of the text file you want to process. Replace'path/to/your/text/file.txt'with the actual path. - The
target_wordvariable is assigned the word entered by the user using theinput()function. - The
count_word_occurrencesfunction is called with thefile_pathandtarget_wordas arguments, and the result is stored in theoccurrencesvariable. - Finally, the program prints the result, showing how many times the
target_wordappears in the file.
3. Case Insensitivity
Both the content of the file and the target word are converted to lowercase using the lower() method. This ensures that the search is case-insensitive. For example, if the target word is “Python” and the file contains “python” or “PYTHON,” they will all be counted as occurrences.
Input/ Output
