typestar

wordcount.go in Go

A complete word-frequency program: read stdin, tally, sort, print.

package main

import (
    "bufio"
    "fmt"
    "os"
    "sort"
    "strings"
)

func main() {
    counts := make(map[string]int)
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    for scanner.Scan() {
        word := strings.ToLower(strings.Trim(scanner.Text(), ".,!?;:"))
        if word != "" {
            counts[word]++
        }
    }
    words := make([]string, 0, len(counts))
    for w := range counts {
        words = append(words, w)
    }
    sort.Slice(words, func(i, j int) bool {
        return counts[words[i]] > counts[words[j]]
    })
    for _, w := range words {
        fmt.Printf("%6d  %s\n", counts[w], w)
    }
}

Keywords and builtins used here

The run, in numbers

Lines
31
Characters to type
540
Tokens
167
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 91 seconds.

Type this snippet

Step 1 of 1 in Encore, step 19 of 19 in Interfaces & generics.

← Previous