You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3:利用正则表达式实现复杂文件名列表排序

Alright, I get your problem—you've got a set of filenames that need a specific custom sort order, but os.listdir() is spitting them out in the wrong sequence. Let's fix this with regex and Python's sorted() function, which lets you define a custom sorting key to match your desired order.

Step 1: Break Down the Filename Patterns

Your files fall into two consistent formats:

  • Standard: aaaa 4b [MAIN_NUM]b.txt (e.g., aaaa 4b 123b.txt)
  • Variant: aaaa 4b 129 ([SUB_NUM]c)b.txt (e.g., aaaa 4b 129 (123c)b.txt)
    The core requirement is to sort first by the main number, and for files sharing the same main number (like the 129 variants), place the parenthesized files before the standard 129b.txt.

Step 2: Implement the Custom Sort Solution

Here's a complete code snippet that uses regex to extract sorting keys and reorders your file list correctly:

import re
import os

def get_sort_key(filename):
    # Regex pattern to match both filename formats
    pattern = r'aaaa 4b (\d+)(?: \((\d+)c\))?b\.txt'
    match = re.match(pattern, filename)
    
    if match:
        # Extract the main numeric group (e.g., 123, 129)
        main_num = int(match.group(1))
        # Extract sub-number if present; use infinity for standard files to push them to the end of the same main_num group
        sub_num = int(match.group(2)) if match.group(2) else float('inf')
        return (main_num, sub_num)
    
    # Push any unrecognized files to the very end
    return (float('inf'), float('inf'))

# Replace with your target directory path
target_directory = "/path/to/your/files"
unsorted_files = os.listdir(target_directory)

# Apply custom sorting
sorted_files = sorted(unsorted_files, key=get_sort_key)

# Print to verify the correct order
for file in sorted_files:
    print(file)

Step 3: Why This Works

  • The regex captures two parts of each filename: the main number, and an optional sub-number from the parentheses.
  • For standard files (no parentheses), we set sub_num to float('inf')—this ensures that when two files have the same main number, the variant files (with finite sub-numbers) will always come first.
  • Any files that don't match your format are sorted to the end, so they won't disrupt your desired sequence.

Expected Output

When you run this code, the sorted list will exactly match your desired order:

aaaa 4b 123b.txt
aaaa 4b 124b.txt
aaaa 4b 125b.txt
aaaa 4b 126b.txt
aaaa 4b 127b.txt
aaaa 4b 128b.txt
aaaa 4b 129 (123c)b.txt
aaaa 4b 129 (124c)b.txt
aaaa 4b 129 (125c)b.txt
aaaa 4b 129 (126c)b.txt
aaaa 4b 129 (127c)b.txt
aaaa 4b 129b.txt
aaaa 4b 130b.txt
aaaa 4b 131b.txt
aaaa 4b 132b.txt

内容的提问来源于stack exchange,提问作者Eric Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:08:18