Python 文件名排序(字符串、數字混合)

為節省閲讀時間,直接上例子,若符合排序模型請繼續閲讀。

source:['a1_1', 'a1_2', 'a11_1', 'a11_2','a2_1', 'a2_4', 'b1_1', 'b2_1', 'b11_1', 'b3_1']

result:['a1_1', 'a1_2', 'a2_1', 'a2_4', 'a11_1', 'a11_2', 'b1_1', 'b2_1', 'b3_1', 'b11_1']

 

附上Python代碼(可直接複製):

import os

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False

def find_continuous_num(astr, c):
    num = ''
    try:
        while not is_number(astr[c]) and c < len(astr):
            c += 1
        while is_number(astr[c]) and c < len(astr):
            num += astr[c]
            c += 1
    except:
        pass
    if num != '':
        return int(num)

def comp2filename(file1, file2):
    smaller_length = min(len(file1), len(file2))
    continuous_num = ''
    for c in range(0, smaller_length):
        if not is_number(file1[c]) and not is_number(file2[c]):
            # print('both not number')
            if file1[c] < file2[c]:
                return True
            if file1[c] > file2[c]:
                return False
            if file1[c] == file2[c]:
                if c == smaller_length - 1:
                    # print('the last bit')
                    if len(file1) < len(file2):
                        return True
                    else:
                        return False
                else:
                    continue
        if is_number(file1[c]) and not is_number(file2[c]):
            return True
        if not is_number(file1[c]) and is_number(file2[c]):
            return False
        if is_number(file1[c]) and is_number(file2[c]):
            if find_continuous_num(file1, c) < find_continuous_num(file2, c):
                return True
            elif find_continuous_num(file1, c) > find_continuous_num(file2, c):
                return False


    # if file1 < file2:
    #     return True
    # else:
    #     return False

def sort_insert(lst):
    for i in range(1, len(lst)):
        x = lst[i]
        j = i
        while j > 0 and lst[j - 1] > x:
            # while j > 0 and comp2filename(x, lst[j-1]):
            lst[j] = lst[j - 1]
            j -= 1
        lst[j] = x
    return lst

def sort_insert_filename(lst):
    for i in range(1, len(lst)):
        x = lst[i]
        j = i
        # while j > 0 and lst[j-1] > x:
        while j > 0 and comp2filename(x, lst[j - 1]):
            lst[j] = lst[j - 1]
            j -= 1
        lst[j] = x
    return lst

def file_name_sort(all_file_list):
    new_list = []
    return new_list

#demo
print(sort_insert_filename(['a1_1', 'a1_2', 'a11_1', 'a11_2','a2_1', 'a2_4', 'b1_1', 'b2_1', 'b11_1', 'b3_1']))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章