Python Program to find frequency of a word in a Text File

Python Program to find frequency of a word in a Text File

In this article, we will be solving question based on data file handling in Python. According to the question we have to find the number of times a particular word present in a text file or you can see Python program to find frequency of a word in a Text File.

If you like the article content, then share it in your coding groups so that more people can take advantage of the content. So, without wasting any time let's solve this question.

Question - Write a Python Program to find frequency of a word in a Text File

Python Program to find frequency of a word in a Text File


Logic and Explanation

Question - Write a Python Program to find frequency of a word in a Text File

Python Program to find frequency of a word in a Text File - In this program we have to find the frequency of a word in a text file. So, first let's take input from the user the word whose frequency he want to find. Here we are storing this number in variable 'k'. 

Also, let's declare a variable count to count the number of words. As we will come across the word in the text file we will add one to this variable. So, we declare this variable with initial value of 0.

k = input("Enter the word")
count = 0


After this, we will be going to read the text file. So, first we will open the text file in read mode. Then, I will be reading the whole text in it at once and then we will store it in data variable. 

Then, we will iterate through this string word by word. For this we will be splitting the string at whitespace. By using string built-in method split. we will split the string and it will return us a list of strings splitting at whitespace. 

Then we will be iterating through this list and using if condition we will check for it's match with the word stored in k. If they are equal, then we will increase the value of count variable by one.

That's all. Here's the code for the same.

k = input("Enter the word")
count = 0
with open("content.txt","r") as f:
    data = f.read()
    for word in data.split():
        if word == k:
            count += 1
print(count)

So, I hope you liked the article and you would have found the content of the article useful and helpful for you. Share this article in your coding communities so that more people can take advantage of the content. Also, In case of any doubt feel free to ask in the comments below.

For More Such Python Programs - Click Here

Enjoy Coding!!!


Also Read :-

Extract Phone Number Details Using Python






For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment (0)

Previous Post Next Post