Golang統計文件中單詞出現的頻率

本文主要介紹通過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)
    }
}

一起學習,共同進步。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章