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

问题描述 投票:0回答:3

我正在尝试搜索文件列表,查找单词“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])
python regex list file-read
3个回答
1
投票

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

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

1
投票

您可能会发现在这里使用

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)

0
投票

从pathlib导入路径 进口重新

colos_files = [(Path.cwd() / "colos").iterdir() if path.is_file() 中路径的路径] 对于 colos_files 中的 colos_file: 使用 colos_file.open("r",encoding="utf-16") 作为文件: 使用 (Path.cwd() / "colos-out" / colos_file.name).open("w",encoding="utf-8") 作为输出文件: 对于 re.findall('word1(.*?)word2', file.read()) 中的文本: outfile.write(f"{文本} ”)

此方法使用 re.findall 来抓取字符串中 2 个常见或重复单词之间的单词。它遍历包含您要搜索的所有文件的一个文件夹,然后将结果输出到与原始文件名相同的另一个文件夹中。

当您有 250 多个 xml 文件并且想要提取 和 等键之间的措辞时,这尤其方便。<\Text>

colos_files 是我要重新查找的所有文件所在的目录。

colos 是实际的文件夹名称。

colos_file 是实际文件夹名称中的“文件名”。

colos-out 是存储 re.findall 版本的新文件夹。

text 是 re.findall 找到的 word1 和 word2 之间的单词。

© www.soinside.com 2019 - 2024. All rights reserved.