如何使用 GO 计算文本文件中只出现一次的字符串数量? 我读过golang的一些包描述,也许我应该使用bufio.NewScanner一次一行读取传入文件的内容。然后我尝试使用map来统计每个字符串的出现次数:
stringcount := make(map[string]int)
如何更新这张空 map 的数据?例如,如果文件中的第一个字符串是“hello”,如何使stringcount[“hello”] = 1?
这是我的尝试:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
frequencyofWord := map[string]int{}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
s := strings.Fields(scanner.Text()) //one more question : is strings.Fields used correctly here?
countSingleton(s)
}
func countSingleton(a []string) {
//here how to update the map according to the text read ?//
}
最佳答案
使用bufio.NewScanner
要分开线条,请使用 strings.Fields
获取单词,然后使用 yourMap[theWord]++
计算单词数。
关于string - 使用 Golang 计算文本文件中单例的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21373408/