gpt4 book ai didi

python正则表达式收集具有相同 header 的文件

转载 作者:行者123 更新时间:2023-11-30 22:16:23 26 4
gpt4 key购买 nike

我正在尝试编写一个函数,该函数返回包含相同起始名称的图像列表。这是工作目录的屏幕截图。

enter image description here

def get_image_sequence(filepath):
'''
Description:
Returns list of images contained in the same seq
Args:
filepath(str): Path to a frame in the sequence
'''
seq = []

if not os.path.isfile(filepath):
return []

basename = os.path.basename(filepath).split('.')[0]
directory = os.path.dirname(filepath)

matcher = re.compile(r'^(?P<header>[\w\-.]*(?:[.]|[_]))*(?P<padding>\d+)(?P<tail>[.][A-Za-z]{1,4}$)')

for file in sorted(os.listdir(directory)):
reMatch = matcher.match(file)
if reMatch:
print reMatch.group('header'), reMatch.group('padding'), reMatch.group('tail')

return seq

当我运行脚本尝试收集与名为 TEST_0102_000_010_fx_playblast_v08.0018.jpg 的文件序列关联的图像时,我立即得到以下输出:

TEST_ 0102 .jpg
TEST_0102_000_010_fx_playblast_v08. 0010 .jpg
TEST_0102_000_010_fx_playblast_v08. 0011 .jpg
TEST_0102_000_010_fx_playblast_v08. 0012 .jpg
TEST_0102_000_010_fx_playblast_v08. 0013 .jpg
TEST_0102_000_010_fx_playblast_v08. 0014 .jpg
TEST_0102_000_010_fx_playblast_v08. 0015 .jpg
TEST_0102_000_010_fx_playblast_v08. 0016 .jpg
TEST_0102_000_010_fx_playblast_v08. 0017 .jpg
TEST_0102_000_010_fx_test_v08. 0028 .jpg
TEST_0102_000_010_fx_test_v08. 0029 .jpg
TEST_0102_000_010_fx_test_v08. 0030 .jpg

我想知道是否有办法可以将基本名称插入到re中,即TEST_0102_000_010_fx_playblast_v08。这样,reMatch 仅在每个文件的前缀匹配时才测试 True,然后返回:

TEST_0102_000_010_fx_playblast_v08. 0010 .jpg
TEST_0102_000_010_fx_playblast_v08. 0011 .jpg
TEST_0102_000_010_fx_playblast_v08. 0012 .jpg
TEST_0102_000_010_fx_playblast_v08. 0013 .jpg
TEST_0102_000_010_fx_playblast_v08. 0014 .jpg
TEST_0102_000_010_fx_playblast_v08. 0015 .jpg
TEST_0102_000_010_fx_playblast_v08. 0016 .jpg
TEST_0102_000_010_fx_playblast_v08. 0017 .jpg

最佳答案

这是您要找的吗:

matcher = re.compile(r'^(?P<header>' + basename + ')\.(?P<padding>\d+)(?P<tail>[.][A-Za-z]{3})$')

Demo

请注意,我还稍微修改了填充和尾部正则表达式。

关于python正则表达式收集具有相同 header 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49967832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com