Word Frequency From Fields

Rank repeated words from log lines by splitting each line with strings.Fields and accumulating counts in a map keyed by the word.

GoData Integrity

Code

gosnippet
48 lines
package main

import (
	"fmt"
	"sort"
	"strings"
)

func wordCounts(lines []string) map[string]int {
	counts := make(map[string]int)
	for _, line := range lines {
		// Fields 按连续空白切分并丢弃空串:多空格/制表符都算分隔
		for _, word := range strings.Fields(line) {
			counts[strings.ToLower(word)]++
		}
	}
	return counts
}

type entry struct {
	word  string
	count int
}

func main() {
	logLines := []string{
		"deploy api failed",
		"retry	deploy  api",
		"API up",
	}
	counts := wordCounts(logLines)

	ranked := make([]entry, 0, len(counts))
	for word, count := range counts {
		ranked = append(ranked, entry{word, count})
	}
	// 计数降序、同数按词升序:输出稳定可复现
	sort.Slice(ranked, func(i, j int) bool {
		if ranked[i].count != ranked[j].count {
			return ranked[i].count > ranked[j].count
		}
		return ranked[i].word < ranked[j].word
	})

	for _, e := range ranked {
		fmt.Printf("%d x %s\n", e.count, e.word)
	}
}

How it works

Word Frequency From Fields comes down to the functions wordCounts and main.

A single loop drives the file — for _, line := range lines.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: func wordCounts(lines []string) map[string]int

Running the file executes main, which drives wordCounts in order.

Key statements

func wordCounts(lines []string) map[string]int {
counts := make(map[string]int)
for _, line := range lines {
// Fields 按连续空白切分并丢弃空串:多空格/制表符都算分隔
for _, word := range strings.Fields(line) {
counts[strings.ToLower(word)]++
}
}
return counts
}
ranked = append(ranked, entry{word, count})
for _, e := range ranked {
fmt.Printf("%d x %s\n", e.count, e.word)
}

Interactive Tools for This Topic

FAQ

How do you run Word Frequency From Fields?
The file is self-contained: run it directly, no dependencies to install beforehand.