Word frequency count in Python
The bread-and-butter pattern for tallying anything with a dict.
def word_count(text):
counts = {}
for word in text.lower().split():
word = word.strip(".,!?;:")
if word:
counts[word] = counts.get(word, 0) + 1
return counts
How it works
- Lowercases the text and splits it into words.
stripremoves surrounding punctuation from each word.get(word, 0)defaults new words to zero before counting up.
Keywords and builtins used here
defforifreturnword_count
The run, in numbers
- Lines
- 7
- Characters to type
- 157
- Tokens
- 53
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 33 seconds.
Step 8 of 10 in Collections, step 30 of 72 in Language basics.