Write a function called ordered_freq_distribution with two parameters: infile an
ID: 3670596 • Letter: W
Question
Write a function called ordered_freq_distribution with two parameters: infile
and ordered distfile. The first parameter, infile, is the name of the file for which we
want to compute the frequency distribution. The second parameter, ordered distfile
is the name of the file into which the frequency distribution is to be written in sorted order
of the frequency. That is, the words should be printed into the file in decreasing order of
frequency. If several words have the same frequency, they should be listed in alphabetical
order. Use string formatting to make sure that the output in ordered distfile is neatly
formatted.
Once again, in order to carry out this task, you must first create a dictionary to store
the frequency distribution by calling the helper function freq _dictionary described in
#(3) below. Remember to close all files used in the function.
this is how the function should be called---> ordered_freq_distribution('anyfile.txt','ordfreq.txt') You can use any txt file to test out the function.
This is the sample output. this is an example of how it should work. any txt file can be used to test this function
you 4
in 3
have 2
your 2
any 1
brains 1
can 1
choose 1
direction 1
feet 1
head 1
shoes 1
steer 1
yourself 1
I have the helper fucntion that will be required for thi function. this has to be done in python. Your help will be appreciated. Thank you
Explanation / Answer
Code:
from operator import itemgetter
def ordered_freq_distribution(infile,outfile):
fhand=open(infile,'r')
d={}
for i in fhand:
words=i.split()
for word in words:
if word not in d:
d[word]=1
else:
d[word]+=1
fhand.close()
fhand=open(outfile,'w')
for word in sorted(sorted(d, key=itemgetter(0)),key=d.get, reverse=True):
fhand.write(word+" "+str(d[word])+" ")
ordered_freq_distribution('anyfile.txt','ordfreq.txt')
Input:(anyfile.txt)
ara vi jay a ke ti neni ka lya n ven ka sh you me i can get you me ara vi
Output:(ordfreq.txt)
ara 2
ka 2
me 2
vi 2
you 2
a 1
can 1
get 1
i 1
jay 1
ke 1
lya 1
neni 1
n 1
sh 1
ti 1
ven 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.