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.
What you’ll build
Section titled “What you’ll build”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.mojo run wordcount.mojo story.txt 5You’ll see:
35 words, 19 different
WORD COUNT------------------the 9cat 3dog 3happy 2mat 25 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.
Step 1: Split text into words
Section titled “Step 1: Split text into words”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 wordsThat’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.
Step 2: Normalize each word
Section titled “Step 2: Normalize each word”“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 PUNCTUATIONis a constant: the characters we treat as punctuation, written once at the top.\"is a double quote inside the string.don'tkeeps its apostrophe, becausestriponly 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, sonormalizeaccepts both aStringand theStringSpanviews thatsplit()gives us.String(...)turns the stripped view into a real string, andlower()returns a newString.
Step 3: Count with a Dict
Section titled “Step 3: Count with a Dict”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 5cat 3sat 1on 1mat 1was 1happy 2very 1then 1dog 1came 1and 1ran 1The important lines:
counts.get(word, 0)returns the count if the word is there, and0if it isn’t. That’s the same trick as Python’sdict.get(word, 0). It never raises, socount_wordsdoesn’t needraises.return counts^moves the dictionary out of the function. ADictcan’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.keyand.value. The Dict reference promises that iteration follows insertion order, like Python’sdict, which is why the words come out in the order they first appeared.
Step 4: Sort by count, then by word
Section titled “Step 4: Sort by count, then by word”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_initstruct 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_initstruct 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 5cat 3happy 2and 1sat 1sort 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.
Step 5: Print a top-N table
Section titled “Step 5: Print a top-N table”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_initstruct 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 5cat 3happy 2and 1min(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_initstruct 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:
mojo run wordcount.mojo story.txtYou’ll see:
35 words, 19 different
WORD COUNT------------------the 9cat 3dog 3happy 2mat 2on 2sat 2again 1and 1came 1And when something’s wrong, you get a clear message instead of a crash:
mojo run wordcount.mojo nope.txtCan't read nope.txt: Failed to open file 'nope.txt': No such file or directoryThat 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.
Common mistakes
Section titled “Common mistakes”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: 1Use 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 moduleThe 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.
Ideas to extend it
Section titled “Ideas to extend it”- Ignore common words. Skip “the”, “and”, “a” and friends with a
Setof stop words. (Practice 1.) - Count lines and characters too, like the Unix
wctool.text.splitlines()andtext.count_codepoints()will help. (Practice 2.) - Read piped text. Accept
cat story.txt | mojo run wordcount.mojowhen no file is given. The Mojo Reading Input lesson shows how to read all of standard input at once (repeatedinput()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").
Practice
Section titled “Practice”1. Ignore stop words
Section titled “1. Ignore stop words”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 1dog 1sat 1mat 1A Set answers “is this word in here?” quickly, however many stop words you add. Because we check after normalizing, The is skipped too.
2. Lines, words and characters
Section titled “2. Lines, words and characters”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 characters1 lines, 3 words, 12 characterscount_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 lightStringSpanviews; wrap one inString(...)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] += 1raises for a new word. - Return a local
DictorListwith^, and read entries withitem.key/item.value. sort(list, compare_fn)sorts in place with your own rule. Add a tie-breaker, becausesortisn’t stable.argv()gives the arguments,open(path, "r").read()reads a file, and errors go tostderrwithexit(1).
Next up: Project: To-Do List CLI, a small command-line tool that saves your tasks to a file.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- String: Mojo std library:
split,strip,lower,ascii_ljustand the rest of the string methods. - Dict: Mojo std library:
get,items, the insertion-order promise, andDictKeyError. - sort: Mojo std library: sorting in place with a compare function.
- argv: Mojo std library: reading command-line arguments.
- open: Mojo std library: opening files for reading and writing.