regex 读取多个文件,搜索字符串并存储在列表中

yx2lnoni  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(72)

我正在搜索一系列文件,寻找“类型”和后面的单词。然后将它们放入一个带有文件名的列表中。例如,这就是我正在寻找的。

File Name, Type

[1.txt, [a, b, c]]
[2.txt, [a,b]]

我的当前代码返回每种类型的列表。

[1.txt, [a]]
[1.txt, [b]]
[1.txt, [c]]
[2.txt, [a]]
[2.txt, [b]]

这是我的代码,我知道我的逻辑将返回一个单一的值到列表中,但我不知道如何编辑它,它将只是文件名与类型列表。

output = []
for file_name in find_files(d):
    with open(file_name, 'r') as f:
        for line in f:
            line = line.lower().strip()
            match = re.findall('type ([a-z]+)', line)
            if match:
                output.append([file_name, match])
8fsztsew

8fsztsew1#

学会在适当的循环级别对动作进行分类。在本例中,您说您希望将所有引用累积到一个列表中,但随后您的代码为每个引用创建一个输出行,而不是为每个文件创建一个输出行。改变焦点:

with open(file_name, 'r') as f:
    ref_list = []
    for line in f:
        line = line.lower().strip()
        match = re.findall('type ([a-z]+)', line)
        if match:
            ref_list.append(match)

    # Once you've been through the entire file,
    #   THEN you add a line for that file,
    #    with the entire reference list
    output.append([file_name, ref_list])
wmvff8tz

wmvff8tz2#

您可能会发现在这里使用dict很有用

output = {}
for file_name in find_files(d):
    with open(file_name, 'r') as f:
        output[file_name] = []
        for line in f:
            line = line.lower().strip()
            match = re.findall('type ([a-z]+)', line)
            if match:
                output[file_name].append(*match)

相关问题