Text analysis combines splitting, cleaning and counting.
What to build
A program that counts how often each word appears in a text.
Requirements
- Read all lines of the input until it ends.
- Split into words on spaces, change them to lower case and remove the characters
.,!?;:from both ends of each word. Ignore words that become empty. - Print one line
WORD COUNTper distinct word, with the most frequent first and words with the same count in alphabetical order.
Input
Any number of lines of text.
Output
One line per distinct word.
Constraints
Up to 20 lines of at most 100 characters; English text.
Example
Input:
The cat saw the dog.
The dog saw the cat!
Output:
the 4
cat 2
dog 2
saw 2
Why it works
strings.Fields handles any spacing, and Trim with a set of characters removes punctuation around a word. A map counts the words, and the sort rule decides the order, so the result is the same every time.
Examples
Example 1 · Input
The cat saw the dog. The dog saw the cat!
Expected output
the 4 cat 2 dog 2 saw 2
Example 2 · Input
go go go
Expected output
go 3
Hints
Hint 1
Read the lines with bufio.Scanner and split with strings.Fields; use strings.ToLower and strings.Trim to remove punctuation.
Hint 2
Sort the words with sort.Slice: first by count (higher first), then alphabetically.
Solution
Show one correct solution (try it yourself first)
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
count := make(map[string]int)
for scanner.Scan() {
for _, w := range strings.Fields(scanner.Text()) {
w = strings.Trim(strings.ToLower(w), ".,!?;:")
if w != "" {
count[w]++
}
}
}
words := []string{}
for w := range count {
words = append(words, w)
}
sort.Slice(words, func(i, j int) bool {
if count[words[i]] != count[words[j]] {
return count[words[i]] > count[words[j]]
}
return words[i] < words[j]
})
for _, w := range words {
fmt.Println(w, count[w])
}
}