【问题标题】:Python - Check for exact string in file namePython - 检查文件名中的确切字符串
【发布时间】:2022-12-09 13:47:32
【问题描述】:

我有一个文件夹,其中每个文件都以数字命名(即 img 1、img 2、img-3、4-img 等)。我想通过以下方式获取文件精确的字符串(所以如果我输入“4”作为输入,它应该只返回带有“4”的文件,而不是任何包含“14”或“40”的文件,例如。我的问题是程序返回所有文件,只要它匹配字符串。注意,数字并不总是在同一个位置(对于相同的文件,它在末尾,对于其他文件,它在中间)

例如,如果我的文件夹有 5 个文件 ['ep 4', 'xxx 3', 'img4', '4xxx', 'ep-40', file.mp4, file 4.mp4 ],我只想返回[第 4 集,img4,4xxx,文件 4.mp4]

这是我所拥有的(在这种情况下我只想返回所有 mp4 文件类型)

for (root, dirs, file) in os.walk(source_folder):
    for f in file:
        if '.mp4' and ('4') in f:
            print(f)

试过 == 而不是 in

【问题讨论】:

  • if '.mp4' and ('4') in f 这不是检查多个条件的方法。改用这个:if 'mp4' in f and '4' in f。但是,在这种情况下,“4”已经在“mp4”中,因此特定条件是无用的。

标签: python regex file


【解决方案1】:

我们可以使用 re.search 以及对正则表达式选项的列表理解:

files = ['ep 4', 'xxx 3 ', 'img4', '4xxx', 'ep-40', 'file.mp4', 'file 4.mp4']
num = 4
regex = r'(?<!d)' + str(num) + r'(?!d)'
output = [f for f in files if re.search(regex, f)]
print(output)  # ['ep 4', 'img4', '4xxx', 'file.mp4', 'file 4.mp4']

【讨论】:

  • 他也想要 img4 我想
  • @Jordan 感谢您的更正。
【解决方案2】:

这可以通过以下功能来完成

import os


files = ["ep 4", "xxx 3 ", "img4", "4xxx", "ep-40", "file.mp4", "file 4.mp4"]
desired_output = ["ep 4", "img4", "4xxx", "file 4.mp4"]


def number_filter(files, number):
    filtered_files = []
    for file_name in files:

        # if the number is not present, we can skip this file
        if file_name.count(str(number)) == 0:
            continue

        # if the number is present in the extension, but not in the file name, we can skip this file
        name, ext = os.path.splitext(file_name)

        if (
            isinstance(ext, str)
            and ext.count(str(number)) > 0
            and isinstance(name, str)
            and name.count(str(number)) == 0
        ):
            continue

        # if the number is preseent in the file name, we must determine if it's part of a different number
        num_index = file_name.index(str(number))

        # if the number is at the beginning of the file name
        if num_index == 0:
            # check if the next character is a digit
            if file_name[num_index + len(str(number))].isdigit():
                continue
            else:
                print(file_name)
                filtered_files.append(file_name)

        # if the number is at the end of the file name
        elif num_index == len(file_name) - len(str(number)):
            # check if the previous character is a digit
            if file_name[num_index - 1].isdigit():
                continue
            else:
                print(file_name)
                filtered_files.append(file_name)

        # if it's somewhere in the middle
        else:
            # check if the previous and next characters are digits
            if (
                file_name[num_index - 1].isdigit()
                or file_name[num_index + len(str(number))].isdigit()
            ):
                continue
            else:
                print(file_name)
                filtered_files.append(file_name)

    return filtered_files


output = number_filter(files, 4)

for file in output:
    assert file in desired_output

for file in desired_output:
    assert file in output

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 2014-08-13
    相关资源
    最近更新 更多