英文:
Search for specific word using Go
问题
我是新手学习Go语言,正在尝试编写一个程序,该程序可以将一个Reader对象按单词进行分割,并记录每个单词出现的次数。以下是我目前的代码:
func Occurrences(word string, s io.Reader) (uint, error) {
scanner := bufio.NewScanner(strings.NewReader(s))
// 将Reader对象按单词进行分割
var word_count int // 特定单词的出现次数
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
// 在这里进行比较,判断是否找到了目标单词
if scanner.Text() == word {
word_count++
}
}
// 返回特定单词的出现次数
return uint(word_count), nil
}
我不确定接下来该怎么做。我不知道该用什么与我要搜索的单词进行比较。希望能得到帮助。
英文:
I am new to Go, and am trying to set up a program that splits a Reader object word by word, then records the amount of times the word was found. Here is what I have so far.
func Occurrences(word string, s io.Reader) (uint, error) {
scanner := bufio.NewScanner(strings.NewReader(s))
// Split the reader into words
var word_count int // Number of the specific word found
scanner.Split(budfio.ScanWords)
for scanner.Scan() {
}
}
I am not sure where to go from there. I do not know what to compare the word I am searching for with. Any help is appreciated
答案1
得分: 3
将单词字符串与扫描器中的当前字符串标记进行比较
func Occurrences(word string, r io.Reader) (int, error) {
scanner := bufio.NewScanner(r)
wordCount := 0
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
if scanner.Text() == word {
wordCount++
}
}
return wordCount, scanner.Err()
}
https://play.golang.org/p/gfl1jjM9Bd
英文:
Compare the word string with the current string token in the scanner
func Occurrences(word string, r io.Reader) (int, error) {
scanner := bufio.NewScanner(r)
wordCount := 0
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
if scanner.Text() == word {
wordCount++
}
}
return wordCount, scanner.Err()
}
答案2
得分: 0
最简单的方法是使用map[string]int
,其中键是单词,值是该单词的计数。
您需要在单词首次出现时将其添加到映射中,并在此后每次出现时增加计数。
英文:
The simplest thing is to use a map[string]int
, where the key is the word, and the value is the count for that word.
You would have to add each word to the map the first time it appears, and increment the count every time after that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论