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

标签 python regex

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

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/

相关文章:

python - 如何用包含字符串值的列表填充 Pandas 数据框列

python - opencv中具有一定像素高度、宽度的视频

javascript - 正则表达式删除逗号分隔字符串中的前导零

python - 重新匹配 ('any item from a list' ) 与 python

php - 有多少个字符像空格一样可见,但不是空格字符?

python - 从文件中打印行时出现意外的换行符

python - 通过使用元组索引的 loc 选择通过赋值填充空数据框

Python 请求包 : Handling xml response

python - 递归函数不返回值

python - 递归正则表达式模式 - 在 python 中