我正在搜索一系列文件,寻找“类型”和后面的单词。然后将它们放入一个带有文件名的列表中。例如,这就是我正在寻找的。
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])
2条答案
按热度按时间8fsztsew1#
学会在适当的循环级别对动作进行分类。在本例中,您说您希望将所有引用累积到一个列表中,但随后您的代码为每个引用创建一个输出行,而不是为每个文件创建一个输出行。改变焦点:
wmvff8tz2#
您可能会发现在这里使用
dict
很有用