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

如何编程提取图片文件名指定子串?避免使用魔术数字

优化文件名子串提取方案(避免魔术数字)

针对你需要提取指定前缀图片文件名中从Split/split开始的子串的需求,以下是几种替代魔术数字切片的优化方案:

方案1:基于指定前缀分割字符串

利用字符串split方法,直接以目标前缀为分隔符分割文件名,取分割后的后半部分,无需依赖固定长度:

from pathlib import Path

directory_in_str = "images/"
image_name = "Large_Blue_Ocean"
image_list = []

pathlist = Path(directory_in_str).glob(f'{image_name}*')
for path in pathlist:
    # 直接获取文件名而非完整路径字符串,更精准
    filename = path.name
    # 按前缀分割,只分割一次,取第二部分
    target_substr = filename.split(image_name, 1)[1]
    image_list.append(target_substr)

方案2:使用partition方法分割

partition方法会返回包含分隔符的三元组,取第三部分即可得到目标子串,逻辑更清晰:

from pathlib import Path

directory_in_str = "images/"
image_name = "Large_Blue_Ocean"
image_list = []

pathlist = Path(directory_in_str).glob(f'{image_name}*')
for path in pathlist:
    filename = path.name
    # partition返回 (前缀, 分隔符, 目标子串)
    _, _, target_substr = filename.partition(image_name)
    image_list.append(target_substr)

方案3:基于Split/split关键字定位

如果需要更通用的逻辑(比如前缀可能变化,但始终要提取Split/split及之后的内容),可以通过查找关键字的索引来定位:

from pathlib import Path

directory_in_str = "images/"
image_name = "Large_Blue_Ocean"
image_list = []

pathlist = Path(directory_in_str).glob(f'{image_name}*')
for path in pathlist:
    filename = path.name
    # 忽略大小写查找split的起始索引
    split_idx = filename.lower().find('split')
    if split_idx != -1:
        target_substr = filename[split_idx:]
        image_list.append(target_substr)

以上方案均避免了魔术数字的使用,代码可读性和可维护性更强,同时利用Path对象的name属性直接操作文件名,比转换完整路径字符串更精准。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:30:59