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
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.
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()
}