How to Create Word Frequency Counter in Python

In this tutorial, we will learn how to program "How to Create a Word Frequency Counter in Python." We will focus on counting the frequency of words within a given text. The objective is to safely and accurately count the frequency of each word in a string. A sample program will be provided to demonstrate the coding process.

This topic is easy to understand. Just follow the instructions I provide, and you’ll be able to do it yourself with ease. The program I’ll show you demonstrates the correct way to count the frequency of words in a string. I’ll also provide a simple and efficient method to achieve this. So, let’s start coding!

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================= Word Frequency Counter =================\n\n")
  3.  
  4.     test_str = input("Enter a string: ")
  5.  
  6.  
  7.     print("The original string is : " + str(test_str))
  8.  
  9.  
  10.     res = {key: test_str.count(key) for key in test_str.split()}
  11.  
  12.  
  13.     print("The words frequency : " + str(res))
  14.  
  15.     opt = input("\nDo you want to try again?(yes/no): ")
  16.  
  17.     if opt.lower() == 'yes':
  18.         ret=False
  19.     elif opt.lower() == 'no':
  20.         ret=True
  21.         print("Exiting program....")
  22.     else:
  23.         print("Please enter yes/no:")
  24.         break
  25.  
  26.     if ret == False:
  27.         continue

This code repeatedly prompts the user to enter a string and calculates the frequency of each word in that string. It stores the word counts in a dictionary, displaying the original string alongside the computed frequencies. After each iteration, it asks the user if they wish to try again, allowing for continuous use until the user decides to exit by entering "no."

Output:

There you have it we successfully created How to Create Word Frequency Counter 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

Add new comment