本文主要介紹通過golang實現讀取文件,並對文件中出現的單次頻率進行統計。
package main
import (
"fmt"
"io/ioutil"
"log"
"strings"
)
func main() {
buf,err := ioutil.ReadFile("test.txt")
if err != nil {
log.Fatal(err)
}
statisticTimes := make(map[string]int)
wordsLength := strings.Fields(string(buf))
for counts,word := range wordsLength {
//判斷key是否存在,這個word是字符串,這個counts是統計的word的次數。
word,ok :=statisticTimes[word]
if ok{
word = word
statisticTimes[wordsLength[counts]] = statisticTimes[wordsLength[counts]] + 1
}else {
statisticTimes[wordsLength[counts]] = 1
}
}
for word,counts := range statisticTimes {
fmt.Println(word,counts)
}
}
一起學習,共同進步。