【问题标题】:Using a regular expression to match filenames from a dictionary in python使用正则表达式匹配python中字典中的文件名
【发布时间】:2020-06-02 15:56:18
【问题描述】:

我有一个文件名字典:

dic = {
    'this_file_name':'*this_file_name*.csv',
    'another': '*another*.csv'
    }

我有一条路:

file_path = glob.glob('path/to/files/*')

我正在尝试实现一些在文件夹中查找并查看是否有任何文件与字典中的值匹配的逻辑。

for files in file_path:
    if re.match(dic.values(), files):
        # do stuff with the files

不过我不确定如何实现。

【问题讨论】:

  • 您的字典值是全局变量,而不是正则表达式。为什么不再次使用glob.glob?或者只是glob.glob('/path/to/files/' + dict_value)
  • 我不明白?
  • 您帖子中未提出的问题似乎是如何将*another*.csv 之类的内容转换为正则表达式。我建议你不要尝试。我会使用glob.globglob + fnmatch
  • 或者你问如何修改dic
  • 我有与 dict 值中的模式匹配的文件,我有几个具有不同键值对的 dict。我想匹配匹配模式(字典值)的文件

标签: python dictionary python-re


【解决方案1】:

您的字典值不是有效的正则表达式——它们是 glob。鉴于此,您可以只使用 glob.glob 来匹配文件 (method1)。或者,您可以使用glob.glob 获取目录中的文件列表,并使用fnmatch 测试字典中的每个glob (method2)。最后,您可以将dic 中的值修改为实际上是正则表达式(method3)。

search_dir = '.'

import glob

d1 = {
    'this_file_name': '*this_file_name*.csv',
    'another': '*another*.csv'
}

def method1():
    for k, v in d1.items():
        matches = glob.glob(search_dir + '/' + v)
        if matches:
            print(k, matches)


import fnmatch

def method2():
    names = glob.glob(search_dir + '/*')
    for k, v in d1.items():
        matches = fnmatch.filter(names, v)
        if matches:
            print(k, matches)

import re

d2 = {
    'this_file_name': 'this_file_name.*\.csv$',
    'another': 'another.*\.csv$'
}

def method3():
    names = glob.glob(search_dir + '/*')
    for k, v in d2.items():
        matches = [name for name in names if re.search(v, name)]
        if matches:
            print(k, matches)

if __name__ == '__main__':
    method1()
    method2()
    method3()

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 2013-02-11
    相关资源
    最近更新 更多