In: Computer Science
5.30 Develop the function many() that takes as input the name of a file in the current directory (as a string) and outputs the number of words of length 1, 2, 3, and 4. Test your function on file sample.txt.
>>> many('sample.txt')
Words of length 1 : 2
Words of length 2 : 5
Words of length 3 : 1
Words of length 4 : 10
Coding language is python
Below is a screen shot of the python program to check indentation. Comments are given on every line explaining the code.Below is the output of the program: Contents of sample.txt:
Console output:
Below is the code to copy: #CODE STARTS HERE----------------
def many(f_name): word_dict = dict() #Dictionary to store the count with open(f_name) as f: #open file for line in f.readlines(): #Read line by line for word in line.split(): #read word by word word_len = len(word)# calculate the length of the word if word_len<=4: #If word is less than 4 char long, add it to dict #Adds a new word length or updates the existing one word_dict[word_len] = word_dict.get(word_len, 0) + 1 return word_dict #returns the dict result_dict = many("sample.txt") #Function call for tup in sorted(result_dict.items()): #Sort the dict and print the result print("Words of length",tup[0],":",tup[1]) #CODE ENDS HERE------------------