Intermediate · Data & Files · Packages: standard library only

Project 13: Word Frequency Counter

Reads text from standard input, counts how often each word appears, hides common stop words and prints a top list with text bars and simple statistics.

What you will learn

Prerequisites

Packages and installation

Packages: standard library only.

Project structure

Folder layout
word_counter/
  main.py

Step-by-step build

  1. Read the text. sys.stdin.read() returns everything piped into the program as one string.
  2. Tokenize. Lower-case the text and use re.findall(r"[a-z']+", text) to get only words, without punctuation.
  3. Remove stop words. Keep a set of very common words and filter them out with a list comprehension.
  4. Count. Counter(words) builds a dictionary-like object of word counts in one line.
  5. Sort the result. Sort by count descending, then by word, so ties are always in the same order.
  6. Show bars. bar() scales each count against the biggest count so the chart always fits in 20 characters.
  7. Print statistics. Show totals, unique words, sentence count, longest word and the word-length distribution.

Complete source code

main.py
"""Word Frequency Counter - counts words in text read from stdin."""
import re
import sys
from collections import Counter

# Very common words that we usually do not want in the result.
STOP_WORDS = {"the", "a", "an", "and", "of", "to", "in", "is", "it", "that",
              "on", "for", "with", "as", "was", "are", "be", "this", "or"}


def tokenize(text):
    """Lower-case the text and return the list of words (letters and apostrophes)."""
    return re.findall(r"[a-z']+", text.lower())


def count_words(words, skip_stop=True):
    if skip_stop:
        words = [w for w in words if w not in STOP_WORDS]
    return Counter(words)


def bar(count, biggest, width=20):
    """A text bar whose length is relative to the biggest count."""
    return "#" * max(1, round(count / biggest * width))


def print_top(counter, n):
    if not counter:
        print("No words found.")
        return
    items = sorted(counter.items(), key=lambda kv: (-kv[1], kv[0]))[:n]
    biggest = items[0][1]
    width = max(len(w) for w, _ in items)
    for word, count in items:
        print(f"{word:<{width}} {count:>3} {bar(count, biggest)}")


def stats(text, words):
    sentences = [s for s in re.split(r"[.!?]+", text) if s.strip()]
    unique = len(set(words))
    longest = max(words, key=len) if words else ""
    avg_len = sum(map(len, words)) / len(words) if words else 0
    print(f"Words: {len(words)}  Unique: {unique}  Sentences: {len(sentences)}")
    print(f"Longest word: {longest}  Average length: {avg_len:.2f}")


def main():
    text = sys.stdin.read()
    if not text.strip():
        print("Please pipe some text into the program.")
        return
    words = tokenize(text)
    stats(text, words)
    print("\nTop words (stop words removed):")
    print_top(count_words(words), 5)
    print("\nWord length counts:")
    by_len = Counter(len(w) for w in words)
    for length in sorted(by_len):
        print(f"{length:>2} letters: {by_len[length]}")


if __name__ == "__main__":
    main()

Code explanation

Regular expression

[a-z']+ matches one or more letters or apostrophes. Anything else, such as commas and digits, acts as a separator.

Counter

Counter is a dict subclass made for counting. Counter(len(w) for w in words) counts word lengths with the same tool.

Sort key

key=lambda kv: (-kv[1], kv[0]) sorts by count high to low, then alphabetically. The minus sign reverses numbers.

Scaled bars

round(count / biggest * width) gives a proportion of the maximum width. max(1, ...) makes sure every word shows at least one mark.

Sentences

re.split on . ! ? gives pieces; pieces that are only spaces are skipped, so the count is correct.

Expected output

Words: 32  Unique: 16  Sentences: 5
Longest word: sleeps  Average length: 3.38

Top words (stop words removed):
dog     4 ####################
fox     3 ###############
lazy    2 ##########
quick   2 ##########
brown   1 #####

Word length counts:
 1 letters: 1
 2 letters: 5
 3 letters: 16
 4 letters: 3
 5 letters: 5
 6 letters: 2

Common errors and solutions

Error: The program waits and prints nothing
Solution: It is waiting for stdin. Pipe text in (echo 'hi' | python3 main.py) or press Ctrl+D after typing.
Error: Words like don't split wrongly
Solution: Keep the apostrophe in the regex, as done here. Remove it if you do not want contractions.
Error: ValueError: max() arg is an empty sequence
Solution: This happens with no words. The code checks for empty text first and guards the longest-word line.
Error: Capital letters counted as different words
Solution: Always call text.lower() before tokenizing.

Ideas to improve the project