dtxob80644
2016-02-01 03:11 阅读 562
已采纳

读取文件时如何在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 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)
    }
    
    点赞 评论 复制链接分享
  • dongren9966 dongren9966 2016-02-01 06:47

    Less elegant but...

    You can strip the from the end of the string with:

    line, err := buf.ReadString(' ') line = strings.TrimRight(line, "")

    It will remove multiple (^M) and is a no-op if there are none.

    点赞 评论 复制链接分享

相关推荐