Find Most Frequent Word in a .txt File Using Python - Print Word and Count
Introduction
When it comes to text processing, Python is a powerful tool to have in your arsenal. In this article, we will discuss how to find the most frequent word in a .txt file using Python and print both the word and its count.
Steps to Find Most Frequent Word
First, we need to read the contents of the .txt file and store them in a variable. We can use the `open()` function to open the file and the `read()` method to read its contents. We can then split the contents into individual words using the `split()` method and store them in a list.
with open('text_file.txt', 'r') as file:
contents = file.read()
word_list = contents.split()
Next, we need to create a dictionary to store the count of each word. We can use a `for` loop to iterate through the list of words and check if each word is already in the dictionary. If it is, we can increment its count by 1. If it is not, we can add it to the dictionary with a count of 1.
word_count = {}
for word in word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
Now that we have the count of each word, we can find the most frequent word by using the `max()` function with a key argument. We can pass the `word_count` dictionary to the `max()` function and use a lambda function as the key to sort the dictionary by values. We can then print the most frequent word and its count.
most_frequent_word = max(word_count, key=lambda x: word_count[x])
print("Most frequent word: ", most_frequent_word)
print("Count: ", word_count[most_frequent_word])
Conclusion
In this article, we discussed how to find the most frequent word in a .txt file using Python and print both the word and its count. By following the above steps, you can easily process text files and extract useful information from them using Python.
Leave a Reply
Related posts