14. Word frequency
Write a function word_counts(text) that takes a string text and returns a dictionary (a dict) that maps each
word to the number of times it appears in text.
- Words are separated by spaces. There can be more than one space between words, and spaces at the start or end.
- Capitals don't matter:
The,theandTHEare all the word"the". Use the words in lower case as the keys. - If
textis empty, return an empty dictionary{}.
The order of the keys doesn't matter.
Example 1
Input
text = "the cat and the hat"Output
{"the": 2, "cat": 1, "and": 1, "hat": 1}Explanation"the" appears twice, every other word once.
Example 2
Input
text = "Go go GO"Output
{"go": 3}ExplanationIn lower case, all three are "go".
Example 3
Input
text = ""Output
{}ExplanationNo words, so the dictionary is empty.
Constraints
texthas 0 to 100 characters.- It holds only letters and spaces.
Submit also runs 4 more tests you can't see.
Practises Dictionaries (lesson 11).
text.lower().split()gives the words in lower case, and skips extra spaces, at the ends too.- Start with an empty dictionary,
counts = {}, and go through the words one by one. An empty text has no words, so{}is already the answer. counts[word] = counts.get(word, 0) + 1adds one to a word's count:.get(word, 0)gives 0 for a word that isn't in the dictionary yet.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
def word_counts(text):
"""Count how many times each word appears.
text: str, words separated by spaces; may be empty
Returns: dict, each word in lower case -> its count
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.