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

Read multiple files, search for string and store in a list

我正在尝试搜索文件列表,查找单词 'type' 和下一个单词。然后将它们放入带有文件名的列表中。例如,这就是我要找的东西。

File Name, Type

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

我当前的代码return是每种类型的列表。

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

这是我的代码,我知道我的逻辑会 return 将单个值添加到列表中,但我不确定如何编辑它,它只是带有类型列表的文件名。

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])

您可能会发现在这里使用 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)

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

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])