7. Count Words in Reviews
Difficulty: Easy · Topic: Core Python & data structures
Write count_words(text): return a dict from each word in text to how many times it appears.
- Words are separated by any whitespace: spaces, tabs or newlines, one or many.
- Compare words in lowercase:
Chaiandchaiare the same word. - Remove the punctuation
. , ! ? ; : " ' ( )from the start and end of each word (an apostrophe inside a word, as indon't, stays). A "word" that is only punctuation is not counted.
Example: "Great food. Great price!" gives {'great': 2, 'food': 1, 'price': 1}.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
count_words("Great food. Great price!")Expected: {'great': 2, 'food': 1, 'price': 1}
Hints
Hint 1
text.split() with no argument splits on any run of whitespace and never returns empty strings.Hint 2
strip with a string of characters removes any of them from both ends of the word, and only from the ends.Hint 3
counts[w] = counts.get(w, 0) + 1, or counts.setdefault(w, 0) first, adds to a running count.Learn the concepts
- Dict, set and list methods · 7 min read. get, setdefault, views, set operations, append versus extend, remove and slicing, with the traps in each.
More Python problems
- Flatten a Nested List · Easy
- Squares of the Even Numbers · Easy
- Top K Frequent Words · Easy
- Invert a Dictionary · Easy
- Merge Dicts and Sum Shared Keys · Easy
- Group Records by Key · Easy
- Zip Columns into Records · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Sort by Several Keys · Medium
- Fix the Mutable Default Argument · Medium
- Override a Config Without Changing It · Medium
- Keep the Last N Events · Medium