如何从图片路径中提取图片ID?以指定路径提取10877为例
从图片路径提取图片ID的方法
针对你提供的路径/content/gdrive/MyDrive/new/batch/aligned_10877nationalIdFront.png,可以通过以下几种简单方法提取出ID10877:
方法1:字符串分割(以Python为例)
通过拆分路径和文件名,精准定位数字所在的片段:
path = "/content/gdrive/MyDrive/new/batch/aligned_10877nationalIdFront.png" # 提取路径最后一段的文件名 filename = path.split("/")[-1] # 拆分出"aligned_"之后的部分 after_aligned = filename.split("aligned_")[1] # 筛选出其中的数字字符 image_id = ''.join([char for char in after_aligned if char.isdigit()]) print(image_id) # 输出结果:10877
方法2:正则表达式(多语言通用)
利用正则匹配aligned_之后的连续数字,适配性更强,即使文件名格式有细微变动也能生效:
Python实现
import re path = "/content/gdrive/MyDrive/new/batch/aligned_10877nationalIdFront.png" # 匹配"aligned_"后接的一串数字 match_result = re.search(r'aligned_(\d+)', path) if match_result: image_id = match_result.group(1) print(image_id) # 输出结果:10877
JavaScript实现
const path = "/content/gdrive/MyDrive/new/batch/aligned_10877nationalIdFront.png"; const matchResult = path.match(/aligned_(\d+)/); if (matchResult) { const imageId = matchResult[1]; console.log(imageId); // 输出结果:10877 }
内容的提问来源于stack exchange,提问作者Youssef Fahmy
相关产品推荐
相关产品推荐

