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.- while True:
- print("\n================= Word Frequency Counter =================\n\n")
- test_str = input("Enter a string: ")
- print("The original string is : " + str(test_str))
- res = {key: test_str.count(key) for key in test_str.split()}
- print("The words frequency : " + str(res))
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- 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
Add new comment
- 41 views