这是我的代码,用于计算文件中所有唯一单词的出现次数:
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main(){
file, err := os.Open("file1.txt")
if err != nil {
log.Fatal(err)
}
words := make(map[string]int)
/*asking scanner to split into words*/
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanWords)
count := 0
//scan the inpurt
for scanner.Scan() {
//get input token - in our case a word and update it's frequence
words[scanner.Text()]++
count++
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading input:", err)
}
for k, v := range words {
fmt.Printf("%s:%d\n", k, v)
}
}
我必须同时在N个文件上迭代此映射,以便计算所有唯一单词的出现。