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.
Code
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
Word Frequency CounterCount word occurrences in text with Unicode-aware tokenization, optional lowercasing, and a ranked frequency table.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Word Frequency From Fields?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.