2015-05-09 205 views
2

我正在阅读一个目录,并且我注意到如果我有按数字排序的文件(1,2,3,4 ...),那么它似乎使用一些字母顺序。假设我有13个文件(名为1.md,2.md,3.md ...),排序如下:1,10,11,12,13,2,3,4。 ..;我使用产生这一顺序与当前的代码是:在Go中按数字顺序对文件进行排序

files, _ := ioutil.ReadDir(my_dir) 
    for _, f := range files { 
     fmt.Println(f.Name()) 
    } 

我找的是1,2,3,... 9,10,11,12,13

如何排序我可以对这些文件进行严格的数字排序吗?请记住,每个文件都命名为N.md,其中N保证是大于或等于0的整数。

谢谢。

回答

8

您能否根据您的要求实施sort界面和订单?鉴于返回的os.FileInfo元素片段,您可以使用数字顺序而不是字典顺序排列它们。

type ByNumericalFilename []os.FileInfo 

func (nf ByNumericalFilename) Len() int  { return len(nf) } 
func (nf ByNumericalFilename) Swap(i, j int) { nf[i], nf[j] = nf[j], nf[i] } 
func (nf ByNumericalFilename) Less(i, j int) bool { 

    // Use path names 
    pathA := nf[i].Name() 
    pathB := nf[j].Name() 

    // Grab integer value of each filename by parsing the string and slicing off 
    // the extension 
    a, err1 := strconv.ParseInt(pathA[0:strings.LastIndex(pathA, ".")], 10, 64) 
    b, err2 := strconv.ParseInt(pathB[0:strings.LastIndex(pathB, ".")], 10, 64) 

    // If any were not numbers sort lexographically 
    if err1 != nil || err2 != nil { 
     return pathA < pathB 
    } 

    // Which integer is smaller? 
    return a < b 
} 

files, _ := ioutil.ReadDir(".") 

sort.Sort(ByNumericalFilename(files)) 

for _, f := range files { 
    fmt.Println(f.Name()) 
} 

我知道它不是很简洁,但是是一个有效的答案。

+1

我发布我的问题后不久有这个想法;我以不同的方式写了它 - 但非常感谢您的帮助。我已经接受了你的回答,因为如果我使用了它,它会给我我想要的。 – q3d

+1

@BenCampbell,您在上次修改时添加了语法错误。 –

+0

@DaveC谢谢!现场编写代码总是有风险的。 –