Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A function called ordered_freq_distribution with two parameters: infile and orde

ID: 3671803 • Letter: A

Question

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.

I have the helper fuction in that image. Please use correct indentation and this is to be written in Python

Explanation / Answer

from operator import itemgetter, attrgetter
import collections

def freq_dictionary(infile):
    a = open(infile,'r')
    b = {}
    for i in a :
        words = i.split()
        for word in words:
            if word not in b:
                b[word] = 1
            else :
                b[word] += 1
    a.close()
    return b

def ordered_freq_distribution(infile,ordered_distfile):
    od = freq_dictionary(infile)
    d = collections.OrderedDict(sorted(od.items()))
    f = open(ordered_distfile, 'w')
#    d = sorted(d)
    for i in sorted(d,key = d.get,reverse = True) :
        print >>f,'{:30}'.format(i)," ", d[i]
    f.close()

infile = 'text8'
ordered_distfile = 'out1.txt'
ordered_freq_distribution(infile,ordered_distfile)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote