代码改变世界

【Python】模拟windows文件名排序(自动处理文件名中有数字类型排序)

2024-05-13 11:32  狼人:-)  阅读(93)  评论(0编辑  收藏  举报

实现了一种模拟windows排序的python方法,其排序规则为:

  • 不处理浮点数
  • 特殊字符(如:&、$、# 等)排在数字和字母之前;
  • 数字优先于字母排序;
  • 数字是连着的整数,应该按照整数进行排序;
  • 小写字母排在大写字母前面;
  • 英文字符按字母表顺序排序;
 
def custom_sort_key(str_value):
    digital_res = ""
    digital_flag = False
    sort_list = []
    rank_value = []
    for c in str_value:
        c_ascii = ord(c)
        if c_ascii <= 57 and c_ascii >= 48:
            digital_flag = True
            digital_res += c
        else:
            if digital_flag:
                digital_res = int(digital_res)
                rank_value.append((1, digital_res))
                digital_res = ""
                digital_flag = False
            if c_ascii <= 47 or (c_ascii >= 58 and c_ascii <= 64) or (c_ascii >= 91 and c_ascii <= 96) or c_ascii >= 123:
                # special char
                rank_value.append((0, c_ascii))
            elif c_ascii >= 97 and c_ascii <= 122:
                rank_value.append((2, c_ascii))
            elif c_ascii >= 65 and c_ascii <= 90:
                rank_value.append((3, c_ascii))
 
            sort_list.extend(rank_value)
            rank_value = []
 
    return sort_list
 
root_path = r"./path"
image_names = os.path.listdir(root_path )
image_names = sorted(image_names, key=custom_sort_key)
print(image_names)