实现说明
按 Fields 统计词频的核心是函数 wordCounts、main。
驱动整个流程的是 for _, line := range lines 这一个循环。
使用要点
- 执行文件,
main会按顺序走完wordCounts。
常见问题
「按 Fields 统计词频」这个示例怎么运行?
运行这个文件就行;脚本没有任何外部要求。
主签名形如 func wordCounts(lines []string) map[string]int
核心语句
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)
}
代码示例
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)
}
}