這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
本例使用golang實現詞頻統計。步驟:
(1)從檔案中讀取一篇文章。
(2)統計詞頻,按單詞出現的頻率從大到小進行排序。
(3)寫入到檔案中。
註:任何非英文字母的符號均認為是單詞分隔字元(即等同於空格)。
效率:使用本程式統計一篇150W單詞的文章,大約需要70ms.
1.核心代碼:
package wordtestimport ("bytes""fmt""io/ioutil""os""runtime""sort""strings""time")//簡單的詞頻統計任務func CountTestBase(inputFilePath string, outputFilePath string) {//時間開始點start := time.Now().UnixNano() / 1e6//讀取檔案fileData, err := ioutil.ReadFile(inputFilePath)CheckError(err, "read file")var fileText string = string(fileData)//根據CPU核心數新開協程newRountineCount := runtime.NumCPU()*2 - 1runtime.GOMAXPROCS(newRountineCount + 1)//切分檔案parts := splitFileText(fileText, newRountineCount)var ch chan map[string]int = make(chan map[string]int, newRountineCount)for i := 0; i < newRountineCount; i++ {go countTest(parts[i], ch)}//主線程接收資料var totalWordsMap map[string]int = make(map[string]int, 0)completeCount := 0for {receiveData := <-chfor k, v := range receiveData {totalWordsMap[strings.ToLower(k)] += v}completeCount++if newRountineCount == completeCount {break}}//添加進slice,並排序list := make(WordCountBeanList, 0)for k, v := range totalWordsMap {list = append(list, NewWordCountBean(k, v))}sort.Sort(list)//時間結束點end := time.Now().UnixNano() / 1e6fmt.Printf("time consume:%dms\n", end-start)//輸出wordsCount := list.totalCount()var data bytes.Bufferdata.WriteString(fmt.Sprintf("程式執行:%dms\n", end-start))data.WriteString(fmt.Sprintf("文章總單詞數:%d\n\n", wordsCount))for _, v := range list {var percent float64 = 100.0 * float64(v.count) / float64(wordsCount)_, err := data.WriteString(fmt.Sprintf("%s: %d, %3.2f%%\n", v.word, v.count, percent))CheckError(err, "bytes.Buffer, WriteString")}err = ioutil.WriteFile(outputFilePath, []byte(data.String()), os.ModePerm)CheckError(err, "ioutil.WriteFile")}func countTest(text string, ch chan map[string]int) {var wordMap map[string]int = make(map[string]int, 0)//按字母讀取,除26個字母(大小寫)之外的所有字元均認為是分隔字元startIndex := 0letterStart := falsefor i, v := range text {if (v >= 65 && v <= 90) || (v >= 97 && v <= 122) {if !letterStart {letterStart = truestartIndex = i}} else {if letterStart {wordMap[text[startIndex:i]]++letterStart = false}}}//最後一個單詞if letterStart {wordMap[text[startIndex:]]++}ch <- wordMap}//將全文分成n段func splitFileText(fileText string, n int) []string {length := len(fileText)parts := make([]string, n)lastPostion := 0for i := 0; i < n-1; i++ {position := length / n * (i + 1)for string(fileText[position]) != " " {position++}parts[i] = fileText[lastPostion:position]lastPostion = position}//最後一段parts[n-1] = fileText[lastPostion:]return parts}func CheckError(err error, msg string) {if err != nil {panic(msg + "," + err.Error())}}2.一個struct
package wordtesttype WordCountBean struct {word stringcount int}func NewWordCountBean(word string, count int) *WordCountBean {return &WordCountBean{word, count}}type WordCountBeanList []*WordCountBeanfunc (list WordCountBeanList) Len() int {return len(list)}func (list WordCountBeanList) Less(i, j int) bool {if list[i].count > list[j].count {return true} else if list[i].count < list[j].count {return false} else {return list[i].word < list[j].word}}func (list WordCountBeanList) Swap(i, j int) {var temp *WordCountBean = list[i]list[i] = list[j]list[j] = temp}func (list WordCountBeanList) totalCount() int {totalCount := 0for _, v := range list {totalCount += v.count}return totalCount}3.主函數:
package mainimport ("WordsTest/wordtest")func main() {inputFilePath := "files/article.txt"outputFilePath := "files/hanjun-result.txt"wordtest.CountTestBase(inputFilePath, outputFilePath)}