In: Computer Science
Write a python program function to check the frequency of the words in text files. Make sure to remove any punctuation and convert all words to lower case.
If my text file is like this:
Hello, This is Python Program? thAt chEcks% THE freQuency of the words!
When is printed it should look like this:
hello 1
this 1
is 1
python 1
program 1
that 1
checks 1
the 2
frequency 1
of 1
words 1
Explanation:
Here is the code which takes the filename from the user in which the lines are stored.
Then the file is opened and the words are stored inside a list.
Then, all the words are converted to lowercase and all the punctuations are removed from the words.
Then a dictionary maintaining the count of the words is created named d.
Then it is printed at the end using a for loop.
Code:
filename = input("Enter filename: ")
f = open(filename, 'r')
words = f.read().split(" ")
f.close()
d = {}
for i in range(len(words)):
words[i] = words[i].lower()
if(not words[i][-1].isalpha()):
words[i] = words[i][:-1]
if words[i] not in d:
d[words[i]] = 1
else:
d[words[i]] = d[words[i]] + 1
for k, v in d.items():
print(k, v)
Output:
PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!
PLEASE COMMENT IF YOU NEED ANY HELP!