How to Count the Occurrences of a Word in a Text File in Python

In this tutorial, we will learn how to program "How to Count the Occurrences of a Word in a Text File in Python." The objective is to count how many times a specific word appears in a text file. This tutorial will guide you step by step through methods for counting word occurrences. By the end of this tutorial, you will have a solid understanding of how to implement this task effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.

This topic is straightforward and easy to understand. Simply follow the instructions provided, and you will complete it with ease. The program will guide you step by step through the process of counting the occurrences of words inside a text file. So, let's dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. while True:
  2.     print("\n================ Count the Occurrences of a Word in a Text File ================\n")
  3.  
  4.     fname = input("Enter file name: ")
  5.     word = input("Enter word to be searched: ")
  6.     k = 0
  7.  
  8.     try:
  9.         with open(fname, 'r') as f:
  10.             for line in f:
  11.                 words = line.split()
  12.                 for i in words:
  13.                     if i == word:
  14.                         k += 1
  15.  
  16.         print("Occurrences of the word:")
  17.         print(k)
  18.  
  19.     except FileNotFoundError:
  20.         print("File not found!")
  21.  
  22.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  23.     if opt == 'no':
  24.         print("Exiting program...")
  25.         break
  26.     elif opt != 'yes':
  27.         print("Invalid choice. Exiting program...")
  28.         break

This program counts the occurrences of a specific word in a text file. The user provides the file name and the word to search for. The program reads the file line by line, splits each line into words, and compares each word with the target word to calculate how many times it appears. It also handles errors if the file does not exist. After displaying the result, the program allows the user to repeat the process or exit.

Output:

There you have it we successfully created How to Count the Occurrences of a Word in a Text File in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials