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

如何使用glob函数正确筛选指定编号的tif文件?

解决glob匹配数字范围的问题

你的原模式[a-zA-Z]*[0-5].tif会匹配到austin11.tif,是因为[0-5]仅匹配文件名的最后一位数字,而austin11.tif的最后一位是1,符合这个范围。要精准分离1-5和6-36的文件,可使用以下glob模式:

匹配austin1.tif至austin5.tif

使用模式:*[!0-9][1-5].tif
各部分含义:

  • *:匹配任意长度的城市名字符序列
  • [!0-9]:匹配一个非数字字符(确保数字前是城市名的最后一个字母,而非其他数字)
  • [1-5]:匹配1到5的单个数字
  • .tif:固定后缀

对应代码:

root_dir = os.path.join(DIR, "train")
pattern = "*[!0-9][1-5].tif"
images = glob.glob(os.path.join(root_dir, "images", pattern))
print(sorted(images))

匹配austin6.tif至austin36.tif

需要组合两种模式覆盖一位数和两位数的情况:

  1. 一位数6-9:*[!0-9][6-9].tif
  2. 两位数10-36:*[1-3][0-6].tif(十位1-3,个位0-6,刚好覆盖10-36)

对应代码:

root_dir = os.path.join(DIR, "train")
pattern_1digit = "*[!0-9][6-9].tif"
pattern_2digit = "*[1-3][0-6].tif"
images = glob.glob(os.path.join(root_dir, "images", pattern_1digit)) + glob.glob(os.path.join(root_dir, "images", pattern_2digit))
print(sorted(images))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:21:10