Skip to main content

How to count the occurrences of a word in a file in Python

How to count the occurrences of a word in a file in Python.

Here is a step-by-step tutorial on how to count the occurrences of a word in a file using Python.

Step 1: Open the file To begin, you need to open the file that you want to count the occurrences of a word in. You can do this using the open() function in Python. Specify the file path and the mode in which you want to open the file. For example, to open a file in read mode, you can use the following code:

file = open("path_to_file.txt", "r")

Step 2: Read the file Next, you need to read the contents of the file. You can use the read() or readlines() function to do this. The read() function reads the entire file as a single string, while the readlines() function reads the file line by line and returns a list of lines. Here's an example of using readlines():

lines = file.readlines()

Step 3: Close the file After you have finished reading the file, it is good practice to close it using the close() method. This will free up system resources and ensure that the file is properly closed. You can close the file by calling the close() method on the file object:

file.close()

Step 4: Count the occurrences Now that you have the contents of the file, you can count the occurrences of a specific word. Iterate over each line in the lines list and use the count() method to count the occurrences of the word. Here's an example:

word = "example"
count = 0

for line in lines:
count += line.count(word)

print("Occurrences of the word:", count)

This code will iterate over each line in the lines list and use the count() method to count the occurrences of the word. The count is incremented every time the word is found in a line. Finally, it prints the total count of occurrences.

Step 5: Handle case sensitivity (optional) By default, the count() method is case-sensitive. If you want to count the occurrences of a word regardless of its case, you can convert the word and each line to lowercase using the lower() method. Here's an example:

word = "example"
count = 0

for line in lines:
count += line.lower().count(word.lower())

print("Occurrences of the word (case-insensitive):", count)

In this code, both the word and the line are converted to lowercase using the lower() method before counting the occurrences. This ensures that the count is not affected by the case of the word.

That's it! You now know how to count the occurrences of a word in a file using Python. Remember to open, read, and close the file properly, and handle case sensitivity if needed.