🎓 A1Learner
🔍

Python Files Project: Word Counter

A word-count program reads a text file and counts each word in it.

Make and read the paragraph file

This file is the fixture for the project. The program makes it, then reads it back.

with open("paragraph.txt", "w") as f:
    f.write("cats chase mice mice chase cheese cats nap")

with open("paragraph.txt", "r") as f:
    text = f.read()
print(text)

Split into words

split() cuts on spaces by default. The list keeps repeat words.

text = "cats chase mice mice chase cheese cats nap"
words = text.split()
print(words)

Count with a dict

A new word starts at 1. A known word grows by 1.

words = ["cats", "chase", "mice", "mice", "chase", "cheese", "cats", "nap"]
counts = {}
for word in words:
    if word in counts:
        counts[word] += 1
    else:
        counts[word] = 1
print(counts)

Rank the pairs

The key sorts by count, biggest first. The word itself breaks ties from A to Z.

counts = {"cats": 2, "chase": 2, "mice": 2, "cheese": 1, "nap": 1}
ranked = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
print(ranked)

Example

with open("paragraph.txt", "w") as f:
    f.write("cats chase mice mice chase cheese cats nap")

with open("paragraph.txt", "r") as f:
    text = f.read()

counts = {}
for word in text.split():
    if word in counts:
        counts[word] += 1
    else:
        counts[word] = 1

ranked = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))

for word, count in ranked:
    print(f"{word}: {count}")

Key points

  • Use split() to cut a text into words
  • Use a dict to count.
  • The word is the key.
  • The count is the value.
  • Use sorted() with a key to rank the pairs
  • Sort by count first, biggest first.
  • Break ties by word, A to Z.
  • The counter reads a file and tallies each word it finds.

In this example, the program first writes the paragraph file. It then reads the whole text back. split() cuts the text into words. The loop counts each word in the counts dict. sorted() ranks the pairs by count, biggest first. Ties break by word from A to Z. The last loop prints one word and its count per line.

Note

The tie rule matters.

Without it, equal words could swap order between runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Why does the ranking break ties by word?