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

2024-04-25 20:40:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 文件代码nameintxt类型列表for
2条回答

您可能会发现在这里使用^{}很有用

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

相关问题 更多 >

    热门问题