当前位置: 代码迷 >> python >> Python:根据匹配从列表中写入文件
  详细解决方案

Python:根据匹配从列表中写入文件

热度:111   发布时间:2023-07-16 11:11:54.0

请帮忙。 我正在尝试根据字符串匹配从列表列表中编写单独的文件。

下面的列表 X 有 3 个子列表,基于过滤器的匹配,我想过滤这些行并将它们写入单独的文件。

X = ['apple,banana,fruits,orange', 'dog,cat,animals,horse', 'mouse,elephant,animals,peacock']

filter = (fruits, animals)

从 X 中的列表中,我想根据filter中找到的匹配单独编写 csv 文件。

尝试了以下不完整的代码:

def write(Y):
    temp = []
    for elem in Y:
        for n in filter:
            if n in elem:
                temp.append(elem)

预期输出:

cat fruits.csv:
apple,banana,fruits,orange

cat animals.csv
dog,cat,animals,horse
mouse,elephant,animals,peacock

请帮助或建议最好的方法来做到这一点。

提前致谢。

您可以使用键作为文件名从列表中创建字典,然后迭代字典以写入文件:

import re
from collections import defaultdict

X = ['apple,banana,fruits,orange', 'dog,cat,animals,horse', 'mouse,elephant,animals,peacock']
filter = ('fruits', 'animals')

d = defaultdict(list)
for x in X:
    for f in filter:
        if re.search(fr'\b{f}\b', x):
            d[f].append(x)

for k, v in d.items():
    with open(f'{k}.csv', 'w') as fi:
        for y in v:
            fi.write(y)