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

问题描述

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

File Name,Type

[1.txt,[a,b,c]]
[2.txt,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])

解决方法

您可能会发现在此处改用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])