'How to write a function called word_freq that accept a string and uses an accumlation pattern to return a dictionary? [duplicate]
Write a function called word_freq that accepts a string as a formal parameter and uses an accumulation pattern to return a dictionary that contins the number of occurrences for each word in that string. Use the code below to test your function:
s = 'it is what it is and only what it is' print(word_freq(s))If your function is written correctly, the dictionary below will be displayed.
{'it': 3, 'is': 3, 'what': 2, 'and': 1, 'only': 1}
Solution 1:[1]
This should work:
def word_freq(s):
freq = {}
s = s.split(' ')
for i in s:
if i in freq.keys():
freq[i] += 1
else:
freq[i] = 1
return freq
Output for print(word_freq('it is what it is and only what it is')):
{'it': 3, 'is': 3, 'what': 2, 'and': 1, 'only': 1}
What this does is it takes your string s. It defines a dictionary freq that will be used to count the number of times each word is in the string. Then it splits the string everywhere that there is a space, this splits the string into separate words and returns a list. After that it loops over that list, checks if the word is in the dictionary's keys (it, what and the other words will all be keys after the loop has finished). If so, it adds one to the amount of times it occurs. If not, it creates a key for the dictionary, calls it the word, and gives it a value of 1. Finally the function just returns the dictionary freq.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
