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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失