Skip to content

Project: Word Counter

In this project you’ll build a small but real tool: a word counter. You give it a text file, and it tells you which words appear most often. Writers use tools like this to spot words they repeat too much, and it’s the classic first step in a lot of text processing.

Along the way you’ll use strings, dictionaries, structs, sorting, command-line arguments and file I/O. Every step is a complete program, so you can stop at any point, play with it, and then carry on.

Here’s the finished tool counting the words in a three-line file, story.txt:

The cat sat on the mat. The cat was happy, very happy!
Then the dog came in, and the cat ran up the stairs.
"Not again," said the dog. The dog sat on the mat.
Terminal window
mojo run wordcount.mojo story.txt 5

You’ll see:

35 words, 19 different
WORD COUNT
------------------
the 9
cat 3
dog 3
happy 2
mat 2

5 is optional and says how many rows to show. Words with the same count are listed alphabetically, so the output is the same every time.

The first job is to cut the text into words. split() with no arguments splits on any whitespace (spaces, tabs, newlines) and skips the empty bits between them, just like Python’s str.split():

def main():
var text = "The cat sat on the mat. The cat was happy,\nvery happy! Then the dog came, and the cat ran."
var words = text.split()
print(words)
print(len(words), "words")

Output:

[The, cat, sat, on, the, mat., The, cat, was, happy,, very, happy!, Then, the, dog, came,, and, the, cat, ran.]
20 words

That’s a start, but look at the words: The and the are counted as different words, and so are happy, and happy!. We need to clean each word up before we count it.

One detail for later: split() doesn’t copy the text. It returns a List of StringSpans, small views that point into the original string. That’s fast, but when you want to keep a word around (say, as a key in a dictionary), you turn it into a real String.

“Normalize” means “make equal things look equal”. For us that’s two rules: lowercase everything, and strip punctuation from both ends of the word. strip(chars) removes any of the given characters from both ends, and lower() makes a lowercase copy:

comptime PUNCTUATION = ".,!?;:\"'()[]-"
def normalize(word: StringSlice) -> String:
return String(word.strip(PUNCTUATION)).lower()
def main():
var samples: List[String] = ["The", "mat.", "happy,", "\"Hello!\"", "don't", "--"]
for s in samples:
print(t"[{s}] -> [{normalize(s)}]")

Output:

[The] -> [the]
[mat.] -> [mat]
[happy,] -> [happy]
["Hello!"] -> [hello]
[don't] -> [don't]
[--] -> []

A few things to notice:

  • comptime PUNCTUATION is a constant: the characters we treat as punctuation, written once at the top. \" is a double quote inside the string.
  • don't keeps its apostrophe, because strip only touches the ends. That’s exactly what we want.
  • -- becomes empty. It was all punctuation. We’ll skip empty words when counting.
  • The parameter type is StringSlice, so normalize accepts both a String and the StringSpan views that split() gives us. String(...) turns the stripped view into a real string, and lower() returns a new String.

To count, we keep a Dict[String, Int]: each word maps to how many times we’ve seen it. For every word, look up the current count (0 if it’s new), add 1 and store it back:

comptime PUNCTUATION = ".,!?;:\"'()[]-"
def normalize(word: StringSlice) -> String:
return String(word.strip(PUNCTUATION)).lower()
def count_words(text: String) -> Dict[String, Int]:
var counts = Dict[String, Int]()
for raw in text.split():
var word = normalize(raw)
if word != "":
counts[word] = counts.get(word, 0) + 1
return counts^
def main():
var text = "The cat sat on the mat. The cat was happy,\nvery happy! Then the dog came, and the cat ran."
var counts = count_words(text)
for item in counts.items():
print(item.key, item.value)

Output:

the 5
cat 3
sat 1
on 1
mat 1
was 1
happy 2
very 1
then 1
dog 1
came 1
and 1
ran 1

The important lines:

  • counts.get(word, 0) returns the count if the word is there, and 0 if it isn’t. That’s the same trick as Python’s dict.get(word, 0). It never raises, so count_words doesn’t need raises.
  • return counts^ moves the dictionary out of the function. A Dict can’t be copied without you asking, so without the ^ the compiler stops you (see Common mistakes below). The Mojo Moving Values lesson explains why.
  • for item in counts.items() gives you entries with .key and .value. The Dict reference promises that iteration follows insertion order, like Python’s dict, which is why the words come out in the order they first appeared.

A dictionary isn’t sorted by count, so we copy its entries into a List and sort that. A small struct holds one row:

@fieldwise_init
struct WordCount(Copyable, Writable):
var word: String
var count: Int

@fieldwise_init writes the __init__ for us, so WordCount("cat", 3) works. Copyable lets a list hold it, and Writable lets you print it while debugging.

Then we need a rule for “which row comes first”. sort takes a function that gets two items and returns True when the first one should come before the second. Ours says: more counts first, and for equal counts, alphabetical order:

@fieldwise_init
struct WordCount(Copyable, Writable):
var word: String
var count: Int
def comes_first(a: WordCount, b: WordCount) -> Bool:
if a.count != b.count:
return a.count > b.count
return a.word < b.word
def main():
var rows: List[WordCount] = [
WordCount("sat", 1),
WordCount("the", 5),
WordCount("happy", 2),
WordCount("cat", 3),
WordCount("and", 1),
]
sort(rows, comes_first)
for row in rows:
print(row.word, row.count)

Output:

the 5
cat 3
happy 2
and 1
sat 1

sort changes the list in place and returns nothing. Mojo’s List has no .sort() method, and there’s no key= argument like in Python: you always describe the order with a compare function. The Mojo Sorting & Searching lesson has more.

Now let’s put the pieces together and print a neat table. ascii_ljust(12) pads a string with spaces on the right to 12 characters, and ascii_rjust(5) pads on the left, so the numbers line up:

comptime PUNCTUATION = ".,!?;:\"'()[]-"
@fieldwise_init
struct WordCount(Copyable, Writable):
var word: String
var count: Int
def normalize(word: StringSlice) -> String:
return String(word.strip(PUNCTUATION)).lower()
def count_words(text: String) -> Dict[String, Int]:
var counts = Dict[String, Int]()
for raw in text.split():
var word = normalize(raw)
if word != "":
counts[word] = counts.get(word, 0) + 1
return counts^
def comes_first(a: WordCount, b: WordCount) -> Bool:
if a.count != b.count:
return a.count > b.count
return a.word < b.word
def sorted_counts(counts: Dict[String, Int]) -> List[WordCount]:
var rows: List[WordCount] = []
for item in counts.items():
rows.append(WordCount(item.key, item.value))
sort(rows, comes_first)
return rows^
def print_table(rows: List[WordCount], top: Int):
print("WORD".ascii_ljust(12), "COUNT".ascii_rjust(5))
print("-" * 18)
for i in range(min(top, len(rows))):
print(rows[i].word.ascii_ljust(12), String(rows[i].count).ascii_rjust(5))
def main():
var text = "The cat sat on the mat. The cat was happy,\nvery happy! Then the dog came, and the cat ran."
print_table(sorted_counts(count_words(text)), 4)

Output:

WORD COUNT
------------------
the 5
cat 3
happy 2
and 1

min(top, len(rows)) makes sure we don’t run past the end when someone asks for more rows than there are words. The number goes through String(...) first because ascii_rjust is a String method. These padding methods count bytes, not characters, so a word with accents like café would be padded one space short. For English text that’s fine; the Mojo Strings in Depth lesson explains bytes vs characters.

Step 6: Read a file named on the command line

Section titled “Step 6: Read a file named on the command line”

The last step swaps the hard-coded text for a real file. argv() from std.sys gives you the command-line arguments: argv()[0] is the program itself and argv()[1] is the first argument. open(path, "r").read() reads a whole file into a String, and raises if the file can’t be opened. The argv reference and the Mojo File I/O lesson have more.

Here’s the complete program. Save it as wordcount.mojo:

from std.sys import argv, exit, stderr
comptime PUNCTUATION = ".,!?;:\"'()[]-"
@fieldwise_init
struct WordCount(Copyable, Writable):
var word: String
var count: Int
def normalize(word: StringSlice) -> String:
return String(word.strip(PUNCTUATION)).lower()
def count_words(text: String) -> Dict[String, Int]:
var counts = Dict[String, Int]()
for raw in text.split():
var word = normalize(raw)
if word != "":
counts[word] = counts.get(word, 0) + 1
return counts^
def comes_first(a: WordCount, b: WordCount) -> Bool:
if a.count != b.count:
return a.count > b.count
return a.word < b.word
def sorted_counts(counts: Dict[String, Int]) -> List[WordCount]:
var rows: List[WordCount] = []
for item in counts.items():
rows.append(WordCount(item.key, item.value))
sort(rows, comes_first)
return rows^
def print_table(rows: List[WordCount], top: Int):
print("WORD".ascii_ljust(12), "COUNT".ascii_rjust(5))
print("-" * 18)
for i in range(min(top, len(rows))):
print(rows[i].word.ascii_ljust(12), String(rows[i].count).ascii_rjust(5))
def main():
var args = argv()
if len(args) < 2:
print("usage: mojo run wordcount.mojo <file> [rows]")
return
var text = String()
try:
text = open(args[1], "r").read()
except e:
print(t"Can't read {args[1]}: {e}", file=stderr)
exit(1)
var top = 10
if len(args) >= 3:
try:
top = Int(args[2])
except:
print(t"Not a number: {args[2]}", file=stderr)
exit(1)
var counts = count_words(text)
var total = 0
for item in counts.items():
total += item.value
print(t"{total} words, {len(counts)} different")
print()
print_table(sorted_counts(counts), top)

Make a story.txt next to it (the three lines from the top of this page) and run it:

Terminal window
mojo run wordcount.mojo story.txt

You’ll see:

35 words, 19 different
WORD COUNT
------------------
the 9
cat 3
dog 3
happy 2
mat 2
on 2
sat 2
again 1
and 1
came 1

And when something’s wrong, you get a clear message instead of a crash:

Terminal window
mojo run wordcount.mojo nope.txt
Can't read nope.txt: Failed to open file 'nope.txt': No such file or directory

That message goes to stderr, and exit(1) ends the program with exit code 1, so scripts calling your tool can tell that it failed. Run it with no file at all and it prints the usage line.

Adding 1 to a word that isn’t there yet. In Python, counts[word] += 1 raises KeyError for a new word. Mojo does the same: it raises a DictKeyError, and without a try the program stops:

def main() raises:
var counts = Dict[String, Int]()
var words: List[String] = ["the", "cat", "the"]
for word in words:
counts[word] += 1
print(counts["the"])
stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`
Unhandled exception caught during execution: DictKeyError[String]()
mojo: error: execution exited with a non-zero result: 1

Use counts[word] = counts.get(word, 0) + 1, as in Step 3.

Returning the dictionary without ^. A Dict isn’t implicitly copyable:

def count_words(text: String) -> Dict[String, Int]:
var counts = Dict[String, Int]()
for word in text.split():
counts[String(word)] = counts.get(String(word), 0) + 1
return counts
def main():
print(len(count_words("a b a")))
wordcount.mojo:5:12: error: value of type 'Dict[String, Int]' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable'
return counts
^~~~~~
wordcount.mojo:5:12: note: consider transferring the value with '^'
return counts
^
^
wordcount.mojo:5:12: note: you can copy it explicitly with '.copy()'
return counts
^
.copy()
mojo: error: failed to parse the provided Mojo source module

The note gives the fix: return counts^.

Unpacking items like in Python. for word, count in counts.items(): doesn’t compile in Mojo 1.2 (“cannot unpack value … into 2 values”). Loop over item and use item.key and item.value.

  • Ignore common words. Skip “the”, “and”, “a” and friends with a Set of stop words. (Practice 1.)
  • Count lines and characters too, like the Unix wc tool. text.splitlines() and text.count_codepoints() will help. (Practice 2.)
  • Read piped text. Accept cat story.txt | mojo run wordcount.mojo when no file is given. The Mojo Reading Input lesson shows how to read all of standard input at once (repeated input() calls can lose piped lines).
  • Several files. Loop over argv()[1:] and add every file into the same counts.
  • Write the table to a file with open("report.txt", "w").

Change count_words so it skips the words the, a, and and on. Test it on "The cat and the dog sat on a mat" and print the counts.

Hint: from std.collections import Set, then if word != "" and word not in stop:.

Show solution
from std.collections import Set
comptime PUNCTUATION = ".,!?;:\"'()[]-"
def normalize(word: StringSlice) -> String:
return String(word.strip(PUNCTUATION)).lower()
def count_words(text: String) -> Dict[String, Int]:
var stop: Set[String] = {"the", "a", "and", "on"}
var counts = Dict[String, Int]()
for raw in text.split():
var word = normalize(raw)
if word != "" and word not in stop:
counts[word] = counts.get(word, 0) + 1
return counts^
def main():
var counts = count_words("The cat and the dog sat on a mat")
for item in counts.items():
print(item.key, item.value)

Output:

cat 1
dog 1
sat 1
mat 1

A Set answers “is this word in here?” quickly, however many stop words you add. Because we check after normalizing, The is skipped too.

Write a function def summary(text: String) -> String that returns a line like 3 lines, 10 words, 52 characters, the way the Unix wc tool does. Test it on "Hello there\nGeneral Kenobi\n" and on "café au lait". Guess the numbers before you run it.

Hint: len(text.splitlines()), len(text.split()) and text.count_codepoints(). Build the result with String(t"...").

Show solution
def summary(text: String) -> String:
var lines = len(text.splitlines())
var words = len(text.split())
var chars = text.count_codepoints()
return String(t"{lines} lines, {words} words, {chars} characters")
def main():
print(summary("Hello there\nGeneral Kenobi\n"))
print(summary("café au lait"))

Output:

2 lines, 4 words, 27 characters
1 lines, 3 words, 12 characters

count_codepoints() counts characters, not bytes: café au lait has 12 characters but 13 bytes, because é takes two bytes in UTF-8. The newlines count as characters too. And yes, 1 lines isn’t great English: printing line when the count is 1 is a nice extra step.

  • text.split() splits on any whitespace and returns light StringSpan views; wrap one in String(...) to keep it.
  • Normalize before counting: strip(chars) for punctuation at the ends, lower() for case.
  • Count with counts[word] = counts.get(word, 0) + 1; counts[word] += 1 raises for a new word.
  • Return a local Dict or List with ^, and read entries with item.key / item.value.
  • sort(list, compare_fn) sorts in place with your own rule. Add a tie-breaker, because sort isn’t stable.
  • argv() gives the arguments, open(path, "r").read() reads a file, and errors go to stderr with exit(1).

Next up: Project: To-Do List CLI, a small command-line tool that saves your tasks to a file.

Quick check

1. What does "a b\nc".split() give you?
2. Which line safely adds 1 to a word's count, even the first time you see the word?
3. Why does the compare function also compare the words when the counts are equal?
4. You write return counts at the end of count_words. What happens?