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
- Split text into words with regular expressions
- Count items with collections.Counter
- Sort by several keys using a lambda
- Read all of stdin with sys.stdin.read()
- Draw simple text bar charts
Prerequisites
- Strings and string methods
- Lists, sets and dictionaries
- Functions
- Regular expressions basics
- Modules and imports
Packages and installation
Packages: standard library only.
Project structure
word_counter/
main.pyStep-by-step build
- Read the text. sys.stdin.read() returns everything piped into the program as one string.
- Tokenize. Lower-case the text and use re.findall(r"[a-z']+", text) to get only words, without punctuation.
- Remove stop words. Keep a set of very common words and filter them out with a list comprehension.
- Count. Counter(words) builds a dictionary-like object of word counts in one line.
- Sort the result. Sort by count descending, then by word, so ties are always in the same order.
- Show bars. bar() scales each count against the biggest count so the chart always fits in 20 characters.
- Print statistics. Show totals, unique words, sentence count, longest word and the word-length distribution.
Complete source code
"""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: 2Common errors and solutions
Solution: It is waiting for stdin. Pipe text in (echo 'hi' | python3 main.py) or press Ctrl+D after typing.
Solution: Keep the apostrophe in the regex, as done here. Remove it if you do not want contractions.
Solution: This happens with no words. The code checks for empty text first and guards the longest-word line.
Solution: Always call text.lower() before tokenizing.
Ideas to improve the project
- Read a file name from sys.argv instead of stdin
- Add a --top N option with argparse
- Let users supply their own stop word list
- Count two-word phrases (bigrams)
- Write results to a CSV file
- Support non-English letters with \w