In: Computer Science
Write a program that prompts the user for a file name, make sure the file exists and if it does reads through the file, count the number of times each word appears and then output the word count in a sorted order from high to low.
The program should:
the - 7
in - 6
to - 5
and - 4
of - 4
Using Python as program language
Code:-
import re #importing library for splitting purpose
print("Printing the words in descending order based on frequency of
the word in the file") #printing
while(True): #loop until user enters valid file name
filename=input("Enter filename: ") #Asking user to enter file name
and taking filename from user
try:
file=open(filename,"r") #opening file in read mode
break; #if no exception
except: #if invalid filename
print("Invalid Filename Enter Again") #Asking user enter
again
words=re.split('; |, |\*|\n|\s', file.read().lower()) #making all
words to lowercase letters and splitting the text by(; , \n
\s)
file.close() #closing the file
#here I want to sort the list for words in alphabetical order
words.sort() #sort the words list
frequency={} #declaring frequency dictionary
for i in words: #traverse through all the words in words list
if i not in frequency: #if word is not present in dictionary
frequency[i]= 0 #initiate the value with 0
frequency[i]+=1 #increment the count value
dictlist=list(frequency.items()) #here make dictionary to list for
sorting purpose
for i in range(len(dictlist)-1, -1, -1): #bubble sort to sort the
list using values
for j in range(i):
if dictlist[j][1] < dictlist[j+1][1]:
dictlist[j], dictlist[j+1] = dictlist[j+1], dictlist[j]
#swapping
frequency=dict(dictlist) #make updatedlist to dictionary
for i in frequency:
print(i,"-",frequency[i]) #printing key along with value
Code Screenshot:-
OUTPUT:-