Skip to content

Mindcomb · Coding

Count word frequencies in a file

Curated by Mindcomb

Prompt

Write a short Python script that counts how often each word appears in a text file and prints the ten most common, ignoring case and punctuation.

Mindcomb ran and reviewed this comparison for the public library. It was not saved by a community member.

Prompt source
Mindcomb
License
Mindcomb original
Retrieved
Fork this combTry this promptNo winner picked · recorded cost $0.01827
Compare answers word by word

Community preferences

Which answer would you choose? Your preference is separate from the author's pick and appreciation.

Loading community preferences…

Claude Sonnet 5.5

#!/usr/bin/env python3
"""Print the ten most common words in a text file (case- and punctuation-insensitive)."""

import re
import sys
from collections import Counter


def top_words(path, n=10):
    with open(path, encoding="utf-8") as f:
        text = f.read().lower()

    # Match runs of letters, allowing internal apostrophes (e.g. "don't")
    words = re.findall(r"[a-z]+(?:'[a-z]+)*", text)
    return Counter(words).most_common(n)


def main():
    if len(sys.argv) != 2:
        sys.exit(f"Usage: {sys.argv[0]} <textfile>")

    try:
        results = top_words(sys.argv[1])
    except OSError as e:
        sys.exit(f"Error reading file: {e}")

    for word, count in results:
        print(f"{word:<15} {count}")


if __name__ == "__main__":
    main()

Usage:

python word_count.py myfile.txt

How it works:

  • The text is lowercased so "The" and "the" count as the same word.
  • re.findall extracts only alphabetic words, which discards punctuation. The pattern keeps contractions like "don't" together.
  • Counter.most_common(10) returns the ten highest-frequency words, sorted in descending order.

Note: The regex only matches ASCII letters. For text with accented or non-Latin characters, replace the pattern with r"\w+(?:'\w+)*", though this would also match digits and underscores.

Server-recorded answer

Model: claude-sonnet-5-5

4.2s · 574 tok · $0.005356

Gemini 4 Argon

Here is a short Python script using the built-in re and collections modules to achieve this efficiently:

from collections import Counter
import re


def top_ten_words(filename):
    with open(filename, "r", encoding="utf-8") as file:
        # Read file, convert to lowercase, and extract words (ignoring punctuation)
        words = re.findall(r"\b\w+\b", file.read().lower())

    # Count the words and print the top 10
    for word, count in Counter(words).most_common(10):
        print(f"{word}: {count}")


# Replace 'sample.txt' with the path to your text file
top_ten_words("sample.txt")

How it works:

  1. file.read().lower(): Reads the entire file and converts all text to lowercase so "The" and "the" are counted as the same word.
  2. re.findall(r'\b\w+\b', ...): Uses a regular expression to pull out only alphanumeric word characters, automatically stripping away any punctuation and whitespace.
  3. Counter(words).most_common(10): Counts the frequency of every word in the list and returns the top 10 highest counts.

(Note: This will split contractions like "don't" into "don" and "t". If you want to keep contractions intact, change the regex pattern to r"\b[\w']+\b")

Server-recorded answer

Model: gemini-4-argon

7.8s · 399 tok · $0.003518

GPT-5.5

#!/usr/bin/env python3
import re
import sys
from collections import Counter

if len(sys.argv) != 2:
    print(f"Usage: {sys.argv[0]} <textfile>")
    sys.exit(1)

filename = sys.argv[1]

with open(filename, "r", encoding="utf-8") as f:
    text = f.read().lower()

words = re.findall(r"\b\w+\b", text)
counts = Counter(words)

for word, count in counts.most_common(10):
    print(f"{word}: {count}")

Run it like this:

python word_count.py myfile.txt

Server-recorded answer

Model: gpt-5.5-2026-04-23

3.2s · 206 tok · $0.00533

Grok 4.7

import re
from collections import Counter
from pathlib import Path

def top_words(path, n=10):
    text = Path(path).read_text(encoding="utf-8")
    words = re.findall(r"[a-z0-9']+", text.lower())
    for word, count in Counter(words).most_common(n):
        print(f"{count:6d}  {word}")

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} <file>")
        raise SystemExit(1)
    top_words(sys.argv[1])

Usage: python wordcount.py yourfile.txt

It lowercases the text, keeps only letters, digits, and apostrophes as word characters, and prints the ten most frequent words with their counts.

Server-recorded answer

Model: grok-4.7

3.1s · 1,524 tok · $0.004064