或者问题也可能是:获取词袋的 Go 方法是什么?
例如,如果输入是
"This is a big apple tree. I love big big apple! 42"
那么我如何获得带有每个单词计数的 map 输出(并且,如果方便的话,在此过程中进行一些简单的字符串解析,例如只保留字母并降低它们):
{this=1, is=1, a=1, big=3, apple=2, tree=1, i=1, love=1}
一些 Kotlin 代码的简单版本可能是这样的:
fun main(args: Array<String>) {
val inputText = "This is a big apple tree. I love big big apple! 42"
val map = inputText.replace("[^a-zA-Z]+".toRegex(), " ") // only keep letters
.trim()
.toLowerCase()
.split(" ")
.groupingBy { it }
.eachCount()
println(map)
}
Run Code Online (Sandbox Code Playgroud)
给出输出 {this=1, is=1, a=1, big=3, apple=2, tree=1, i=1, love=1}
我想知道做这样的事情的等效 Golang 方式是什么。希望它很快,也很容易阅读。
例如,
package main
import (
"fmt"
"strings"
)
func main() {
text := "This is a big apple tree. I love big big apple! 42"
fields := strings.FieldsFunc(text, func(r rune) bool {
return !('a' <= r && r <= 'z' || 'A' <= r && r <= 'Z')
})
words := make(map[string]int)
for _, field := range fields {
words[strings.ToLower(field)]++
}
fmt.Println(words)
}
Run Code Online (Sandbox Code Playgroud)
游乐场:https : //play.golang.org/p/6J-ptfCoJ8r
输出:
map[tree:1 i:1 love:1 this:1 is:1 a:1 big:3 apple:2]
Run Code Online (Sandbox Code Playgroud)