Boss lesson · Unit 04
A word counter
Split a text into words, count them in a map, sort the keys and report the most common.
What you practise
- Text split into words, counted in a map, sorted and reported: most common first
Try a question from this lesson
Pick one
strings.Fields cuts a text at its spaces and hands back a slice of the words. What does this print?
text := "the cat saw the dog"
words := strings.Fields(text)
fmt.Println(len(words), words[1])Correct answer
5 cat
Why
The text has five words, so the slice has length 5. Index 1 is the second word, "cat". Splitting text into words is the first step of nearly every program that reads what people write.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The plan
The job: read a text and report how often each word appears, most common first.
The plan has three steps, and you know a tool for each. Split the text into words with strings.Fields. Count the words in a map from string to int: counts[w]++. Then put the keys in a fixed order and print the report.
text := "to be or not to be"
counts := make(map[string]int)
for _, w := range strings.Fields(text) {
counts[w]++
}
fmt.Println(counts["to"], counts["or"])
// 2 1Concept
A fixed order: sorted keys
A map has no order, so a report straight from range would change from run to run.
The cure: collect the keys into a slice, then sort the slice. sort.Strings puts a slice of strings into alphabetical order. A range with one variable gives just the keys.
counts := map[string]int{"b": 2, "a": 1}
var keys []string
for k := range counts {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println(keys) // [a b]Concept
Most common first
To print every word, most common first, repeat one move until the map is empty: find the best word, print it, then delete it from the map so that the next round finds the runner-up.
Here counts is the map and keys holds its sorted keys. A deleted key reads as 0, so it can never win again.
for len(counts) > 0 {
best := keys[0]
for _, k := range keys {
if counts[k] > counts[best] {
best = k
}
}
fmt.Println(best, counts[best])
delete(counts, best)
}9 more exercises in the app
- 1× order the lines
- 2× multiple choice
- 1× fill the blanks
- 4× type the answer
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.