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.txtHow it works:
- The text is lowercased so "The" and "the" count as the same word.
re.findallextracts 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.