typestar

word_freq.py in Python

A complete CLI tool: read a file, count words, print a report.

import sys
from collections import Counter
from pathlib import Path


def word_frequencies(text, top=10):
    words = [w.strip(".,!?;:").lower() for w in text.split()]
    counts = Counter(w for w in words if w)
    return counts.most_common(top)


def main():
    if len(sys.argv) != 2:
        print("usage: word_freq.py FILE")
        raise SystemExit(1)
    text = Path(sys.argv[1]).read_text()
    for word, count in word_frequencies(text):
        print(f"{count:6d}  {word}")


if __name__ == "__main__":
    main()

How it works

  1. sys.argv supplies the file path; bad usage exits with code 1.
  2. Counter tallies cleaned, lowercased words.
  3. most_common(top) sorts the report; the main guard runs it.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
470
Tokens
138
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 2 of 5 in Encore, step 69 of 72 in Language basics.

← Previous Next →