Question
Question: For this problem you should write two functions. The first function count_lengths should take a string text, and return a default dictionary containing the
Question:
For this problem you should write two functions. The first function count_lengths should take a string text, and return a default dictionary containing the frequency counts of each word length. Your function should split text up into words based whitespace using the split method, without removing punctuation or changing the case of any of the "words".
The second function top5_word_lengths should take a string text, and return the list of the (up to) five most-frequent word lengths. It should operate by first calling count_lengths over text to generate a dictionary of word lengths, then sorting the word lengths in terms in descending order of frequency, and returning the top 5 (or less in the instance that there aren't 5). In the case of a tie in frequency, the word lengths should be sub-sorted in descending order of word length.
The two functions will be tested separately.
top5_word_lengths should return word-lengths in descending order in the event that they have the same frequency. If there are fewer than 5 word lengths it should return a shorter list of the sorted word lengths.
Your program should behave as follows:
>>> count_lengths("one one was a racehorse two two was one too")
defaultdict(, {1: 1, 3: 8, 9: 1})
>>> top5_word_lengths("one one was a racehorse two two was one too")
[3, 9, 1]
>>> top5_word_lengths("buffalo buffalo buffalo chicken buffalo")
[7]
>>> top5_word_lengths("the quick brown fox jumped over a lazy dog")
[3, 5, 4, 6, 1]
Try running your program on the speeches by copy-pasting them from speeches.txt as an argument to your function. Compare with your classmates. Is Trump's language simpler?
My incomplete code:
from collections import defaultdict
def count_lengths(text): answer = defaultdict(int) with open("speeches.txt") as f: for line in text: for word in line.split(): l = len(word) if l not in answer: answer[l] = 0 answer[l] += 1 return answer
def top5_word_lengths(text): items = [] a = count_lengths.items() # Most_frequence = firstly need to find out the most frquent len(word) # Same_frequence = then arrange the rest in descending order when they have same frequency # Return lst(Most_frequence, Same_frequence)
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started