A function called freq_dictionary with a single parameter infile, the name of th
ID: 3671453 • Letter: A
Question
A function called freq_dictionary with a single parameter infile, the name of the text file for which we want to compute the frequency distribution. The function should first open infile for reading. It should then create a dictionary with key:value pairs, where the key is a word occurring in infile and its associated value is the frequency of that character in the file i.e., the number of times it occurs in the file. Refer to the earlier discussion for our definition of a word. Note that every word occurring in the file should be included in the dictionary (even if they are nonsense words). Words that do not occur in the file should not be included in the dictionary. The function must return the dictionary. Remember to close the file prior to the return statement.
Please use correct indentation and this is to be written in Python
Explanation / Answer
code start:
def freq_dictionary(infile):
ab = {'aaa':'bbb'}
with open(infile,'r') as f:
for line in f:
for word in line.split():
if word in ab:
cnt=int(ab[word])
cnt=cnt+1
ab[word]=str(cnt)
else:
ab[word]='1'
del ab['aaa']
for name, address in ab.items():
print ('{} occured {}'.format(name, address)+' times')
f.close()
return ab
code end:
Explaination : in each iteration of for loop each line is being read and then being splited into separate words, Then program is checking if that word is akready present in dictionaty 'ab'. If it is then just incrementing its value by 1, if not then adding that word with value '1'
For purpose of creation of dictionary variable,we're adding fake entry ['aaa':'bbb'], and then deleting it from dictionary at end
For sake of understanding,I've printed dectionary contents at end. Those line can be removed from program if you dont want it to be printed.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.