dtxob80644 2016-02-01 03:11
浏览 1556
已采纳

读取文件时如何在golang中删除特殊字符?

I have a file like this: Each line represents a Website

1 www.google.com$
2 www.apple.com$
3 www.facebook.com$

I read it in golang like this:

type ListConf struct {
    File  string
    Datas map[string]struct{}
}

func loadListConf(conf *ListConf, path string) {
    file, err := os.Open(path + "/" + conf.File)
    if err != nil {
        fmt.Println("Load conf " + conf.File + " error: " + err.Error())
        return
    }
    defer file.Close()
    conf.Datas = make(map[string]struct{})
    buf := bufio.NewReader(file)
    end := false
    for !end {
        line, err := buf.ReadString('
')
        if err != nil {
            if err != io.EOF {
                fmt.Println("Load conf " + conf.File + " error: " + err.Error())
                return
            } else {
                end = true
            }
        }
        item := strings.Trim(line, "
")
        if item == "" {
            continue
        }
        conf.Datas[item] = struct{}{}
    }
}

But when I search key such like "www.google.com" in the map, it shows that there is not a "www.google.com" in the map.

website := "www.google.com"
if _, ok := conf.Datas[website]; ok {
    fmt.Printf("%s is in the map.", website)
} else {
    fmt.Printf("%s is not in the map.", website)
}

It print "www.google.com is not in the map". I found that a ^M in the end of each key in the map, my question is how can I remove the ^M character?

www.google.com^M
www.apple.com^M
www.facebook.com^M
  • 写回答

2条回答 默认 最新

  • dtqysxw4659 2016-02-01 03:22
    关注

    The default line separator in text files on Windows is a sequence of two characters: . ^M character that you see in your strings is .

    bufio.Scanner can take care of splitting the input into lines in a platform independent way:

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "error reading from the file:", err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路