typestar

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

  1. Lowercases the text and splits it into words.
  2. strip removes surrounding punctuation from each word.
  3. get(word, 0) defaults new words to zero before counting up.

Keywords and builtins used here

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.

Type this snippet

Step 8 of 10 in Collections, step 30 of 72 in Language basics.

← Previous Next →