常用的 Human Sorting with Python

簡單來說,當 sorting 的結果跟預期的不同,可以試一下。其中奧妙就不多說了,附上原始網址,可以研究一下。

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import re, os

def atoi(text):
    return int(text) if text.isdigit() else text

def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    '''
    return [ atoi(c) for c in re.split('(\d+)', text) ]

try:
    dirs = os.listdir(folder)
    dirs.sort(key=natural_keys)
    # just in case we need the reverse order
    #dirs = reversed(dirs)
    for file in dirs:
        if not file.endswith("csv"):
            continue
        csv_path = "%s\\%s"%(folder, file)
        print (csv_path)
except Exception as e:
    print (str(e))

留言

這個網誌中的熱門文章

以樂透為例,用Python統計馬可夫矩陣

將 Jenkins Job 的歷史結果整理出視覺化的 Daily Report mail (一)

如何用 Jenkins API 取得 Job Build Result