我通过获取句子列表的单词频率计数来构建一系列结构。此输出是每个句子中最受欢迎的单词。我在所有句子中都需要它
这是结构:type WordCountStruct struct {
word string
freq int
}
type WordCountStructArray []WordCountStruct
这是WordCountStructArray的示例:[{the 8} {and 8} {to 7} {and 6} {and 6}]
因此,这是每个句子中最常用单词的有序列表。 我需要按键分组,并求和值
对于上述5个样本,这将导致:[{the 8} {to 7} {and 20}]
如果更简单,我可以将结构转换为[] map [string] interface {}?
最佳答案
这样的东西是您想要的吗?
package main
import "fmt"
type WordCountStruct struct {
word string
freq int
}
type WordCountStructArray []WordCountStruct
func main() {
wCounts := WordCountStructArray{
WordCountStruct{"the", 8},
WordCountStruct{"and", 8},
WordCountStruct{"to", 7},
WordCountStruct{"and", 6},
WordCountStruct{"and", 6},
}
fmt.Println(wCounts)
freq := make(map[string]int)
for _, wCount := range wCounts {
freq[wCount.word] += wCount.freq
}
fmt.Println(freq)
}
https://play.golang.org/p/oCqfoCy_W2g