Python program to find the most frequent words in a text file
Here you will get an example to write a Python program to find the most frequent words in a text file. Python program that reads a text file and finds the most frequent words in it.
Input File
Example of Python program to find the most frequent words in a text file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | # Python program to find the most frequent words in a text file # A file named "test.txt", will be opened in reading mode. file = open("test.txt","r") frequent_word = "Btech" frequency = 0 words = [] # Traversing file line by line for line in file: # splits each line into # words and removing spaces # and punctuations from the input line_word = line.lower().replace(',','').replace('.','').split(" "); # Adding them to list words for w in line_word: words.append(w); # Finding the max occurred word for i in range(0, len(words)): # Declaring count count = 1; # Count each word in the file for j in range(i+1, len(words)): if(words[i] == words[j]): count = count + 1; # If the count value is more # than highest frequency then if(count > frequency): frequency = count; frequent_word = words[i]; print("Most repeated word: " + frequent_word) print("Frequency: " + str(frequency)) file.close(); |
reference link geeksforgeeks
Output
Most repeated word: learn
Frequency: 3
Check out our other Python programming examples