英文:
Count the number of singletons in a text file using Golang
问题
如何使用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()) //还有一个问题:这里是否正确使用了strings.Fields?
countSingleton(s)
}
func countSingleton(a []string) {
//在这里如何根据读取的文本更新map?
}
英文:
How can I count the number of strings that occurs exactly once in a text file using GO?
I have read some of the package description of golang, maybe I should use bufio.NewScanner to read the contents of the passed-in file a line at a time. Then I try to use map to count the occurrence of each string:
stringcount := make(map[string]int)
how can I update the data of this empty map? For example, if the first string is "hello" in the file, how to make stringcount["hello"] = 1?
Here is my try:
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 ?//
}
答案1
得分: 2
使用bufio.NewScanner
来分解行,使用strings.Fields
来获取单词,并使用yourMap[theWord]++
来计算单词的数量。
示例:http://play.golang.org/p/3H6gfBlQL5
要获取唯一单词的列表,迭代遍历映射键,并将它们追加到一个切片,然后对它们进行排序。
英文:
Use bufio.NewScanner
to break apart the lines, use strings.Fields
to get the words, and use yourMap[theWord]++
to count the words.
Example: http://play.golang.org/p/3H6gfBlQL5
To get the list of the unique words, iterate over the map keys and append them to a slice, and then sort them.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论