doulao1934 2014-01-27 05:08
浏览 10

使用Golang计算文本文件中的单例数量

How can I count the number of strings that occurs exactly once in a text file using GO? I have read some of the package description of golang, maybe I should use bufio.NewScanner to read the contents of the passed-in file a line at a time. Then I try to use map to count the occurrence of each string:

stringcount := make(map[string]int)

how can I update the data of this empty map? For example, if the first string is "hello" in the file, how to make stringcount["hello"] = 1?

Here is my try:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {

    frequencyofWord := map[string]int{}

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
    }

    s := strings.Fields(scanner.Text()) //one more question : is strings.Fields used correctly here?
    countSingleton(s)

}

func countSingleton(a []string) {
    //here how to update the map according to the text read ?//
}
  • 写回答

1条回答 默认 最新

  • dongzuo9096 2014-01-27 08:15
    关注

    Use bufio.NewScanner to break apart the lines, use strings.Fields to get the words, and use yourMap[theWord]++ to count the words.

    Example: http://play.golang.org/p/3H6gfBlQL5

    To get the list of the unique words, iterate over the map keys and append them to a slice, and then sort them.

    评论

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系