go语言编程圣经里面ioutil.ReadFile方式读取文件,查找重复行时的问题,如果最后一行是相同的,那么读取结果不对

src:
//readFile once read all to memory
package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "strings"
)

func main(){
    counts :=make(map[string]int);
    for _,fileName :=range os.Args[1:]{
        data,err :=ioutil.ReadFile(fileName);
        if err!=nil{
            fmt.Fprintf(os.Stderr,"dup3:%v\n",err);
            continue;
        }
        //fmt.Println((string(data)));
        //fmt.Println(strings.Split(string(data),"\n"))
        //fmt.Println(len(strings.Split(string(data), "\n")));
        dup :=strings.Split(string(data),"\n")
        fmt.Println(dup)
        for i,arg := range dup{
            fmt.Print(i)
            fmt.Println("->"+arg)
        }
        for _,line:=range dup{
            //fmt.Println(line);
            counts[line]++;
        }
        fmt.Println(len(counts))
    }
    for line,n:=range counts{
        if n>0{
            fmt.Printf("%d\t%s\n",n,line);
        }
    }

}
data:
asd
asa
asd
asd
asa
dss
asd
result:
 asd]
0->asd
1->asa
2->asd
3->asd
4->asa
5->dss
6->asd
4
2   asa
1   dss
1   asd
3   asd
已邀请:

haohongfan - talk is expensive, just show code

赞同来自: stephenXu w_hats

我在mac上测试, 没有问题呀, 是不是一楼说的问题?

[asd asa asd asd asa dss asd ]
xxxxxxxxxxxxxxxxxxxxx
0->asd
1->asa
2->asd
3->asd
4->asa
5->dss
6->asd
7->
xxxxxxxxxxxxxxxxxxxxx
map[:1 asa:2 asd:4 dss:1]
4       asd
2       asa
1       dss
1    

a.txt

asd
asa
asd
asd
asa
dss
asd

wshlovercn

赞同来自: stephenXu

windows ?换行符不是 \n 吧。

koalaone

赞同来自:

尝试用 bufio.Reader 的ReadLine方法

要回复问题请先登录注册