A function called freq_distribution with two parameters: infile and distfile. Th
ID: 3671437 • Letter: A
Question
A function called freq_distribution with two parameters: infile and distfile. The first parameter, infile, is the name of the file for which we want to compute the frequency distribution. The second parameter, distfile is the name of the file into which the frequency distribution is to be written in sorted order of the words. That is, the words should be listed in alphabetically sorted order in the output file. Each line of the file should contain the word and its frequency. Use string formatting to make sure the output is neatly formatted.
In order to carry out the above task, you must first create a dictionary to store the frequency distribution. You will do this by calling the helper function freq dictionary described in #(3) below. Remember to close all files used in the function.
For example, suppose poem.txt is the name of a file containing the following poem (courtesy of Dr. Seuss):
You have brains in your head.
You have feet in your shoes.
You can steer yourself in
any direction you choose.
Then, after the function call freq distribution("poem.txt", "freq.txt"), a file called freq.txt should contain the following:
any 1
brains 1
can 1
choose 1
direction 1
feet 1
have 2
head 1
in 3
shoes 1
steer 1
you 4
your 2
yourself 1
This is to be written in Python and please use correct indentation.
Explanation / Answer
#FREQUENCY PARAMETERS
def freq_poem(infile ,distfile):
#INPUT
inf = open(infile, 'r')
indata = inf.read()
poem = {}
#LOOP
for p pn fple:
#CONDITION
if p != '':
poem[p] = poem.get(p,0)+1
file.close()
re = lambda (a1, a2), (b1, b2):cmp((b2, b1), (a2, a1))
sorted(poem.items(), cmp=re)
#TEXT FILE TO CAPTURE
distdata = open(distfile, 'w')
for p,m in poem.items():
#DISPLAY THE ITEMS
distdata.write('%s=%s ',p,m)
#END
distdata.close()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.