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 List<Class>有参构造
  • ¥20 搭建三相栅极电路后高侧浮动地VS存在电容特性
  • ¥20 云卓h12pro 数传问题
  • ¥20 请问有人知道怎么用工艺库里面的sdb文件通过virtuoso导出来library里面每个cell的symbol吗?
  • ¥20 海思 nnie 编译 报错
  • ¥50 决策面并仿真,要求有仿真结果图
  • ¥15 springboot接入微信支付SDK
  • ¥50 大区域的遥感影像匹配 怎么做啊
  • ¥15 求解答:pytorch跑yolov8神经网络受挫
  • ¥20 Js代码报错问题不知道怎么解决