Answered step by step
Verified Expert Solution
Question
1 Approved Answer
def wordFrequency(text): counts = dict() words = text.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts
def wordFrequency(text): counts = dict() words = text.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts
wordFrequency works on a single file. However, to train our model, we will want to calculate word frequencies from multiple files and merge our results into a single dictionary. Write a function called mergeFrequencies that takes a list of dictionaries. mergeFrequencies should return a new dictionary. (The original dictionaries passed into the function should not be modified) The returned dictionary should contain all the keys from the original dictionaries in the lists. (That is, its keys should be a superset of the keys found in the list.) If a key appears in more than one dictionary, then the value associated with the key in the new dictionary should be the sum of all the keys' values. If the key only appears in a single dictionary, then the value should be the same as the keys values For example: a "a": 10, "b": 20, "c": 30) mergeFrequencies(la,bl) 'c':30. 'a': 15. b':21 Remember, Dictionary keys are not ordered so your keys may be displayed in a different order then the ones in this example. That is OK Recall, you can get values out of a dictionary using square brackets: >al'c' 30 And you can check to see if a key exists in a dictionary using in d in a False If you try to get a value for a key which doesn't exist in a dictionary, you will get an error. There are three different ways of dealing with this problem. 1. You can check to see if a key exists in a dictionary before using it 2. You can try to access a key and catch the error with a try / except block (which we'll discuss this technique later in the semester) 3. You can use the dictionary's get method. get allows you to specify a default value to return if the key isn't in the dictionary. e.g. >a.get("z", 100) 100Step 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