Word Count
Write word_count(text) that returns a dictionary mapping each word in the text to the number of times it appears.
- A word is a run of English letters (
atoz, in any case). Every other character (spaces, digits, punctuation, apostrophes) separates words. - Words are compared in lower case:
"The"and"the"are the same word.
Understand the problem
Decide what counts as a word, then count.
How many different words are in "The cat and the hat."? (Remember case and punctuation.)
The words are the, cat, and, hat. The and the are one word, and the full stop is not part of hat. So 4 different words, with the counted twice.
A dictionary counts already holds {"a": 1}. Which line adds one more "a" and also works the first time a word is seen?
counts["a"] += 1counts["a"] = counts.get("a", 0) + 1counts.append("a")
counts["a"] += 1 raises a KeyError for a word that is not yet in the dictionary. counts.get(word, 0) returns 0 for a missing word, so the first time gives 1. (collections.Counter and defaultdict(int) are two other ways.)
Write the solution
Return the dictionary.
def word_count(text):
# Write your code here.
pass
Hint 1: a question to ask yourself
How do you turn the text into a clean list of lower-case words first, so the counting part is simple?
Hint 2: the shape of the answer
Make a lower-case copy, replace every character that is not a letter with a space (or use re.findall), split() it, and count with a dictionary.
Reflect
Solution
def word_count(text):
cleaned = "".join(ch if "a" <= ch <= "z" else " " for ch in text.lower())
counts = {}
for word in cleaned.split():
counts[word] = counts.get(word, 0) + 1
return counts
Another way: regular expression and Counter
import re
from collections import Counter
def word_count(text):
return dict(Counter(re.findall(r"[a-z]+", text.lower())))
What this tests: building a dictionary of counts (the most common dictionary pattern), dict.get with a default, and cleaning text before processing.
Three ways to count: counts[w] = counts.get(w, 0) + 1, collections.Counter(words), and defaultdict(int). Know all three; Counter is the one to reach for.
Clean first, count second. Mixing the cleaning and the counting makes both harder to test.
Cost: O(n) for a text of n characters.
What an interviewer might ask next: Print the five most common words, ties in alphabetical order. (Counter.most_common orders ties by first appearance: see a later problem.)
VISIBLE = 3
CASES = [
(('The cat and the hat.',), {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}, 'case and punctuation'),
(('Hello, hello!',), {'hello': 2}, 'the same word twice'),
(('',), {}, 'empty text'),
(('!!! ...',), {}, 'no letters'),
(('a a a b',), {'a': 3, 'b': 1}, 'repeated letters'),
(("don't stop",), {'don': 1, 't': 1, 'stop': 1}, 'an apostrophe separates words'),
(('Room 101 room',), {'room': 2}, 'digits are not part of a word'),
(('ONE one One',), {'one': 3}, 'all the capital letters'),
]