繁体   English   中英

Python - 遍历列表和字典以获得嵌套列表输出

[英]Python - iterating through list and dictionary to get a nested list output

我有一个字典mydict ,其中包含一些文件名作为键和其中的文本作为值。

我正在从每个文件的文本中提取单词列表。 单词存储在列表mywords

我尝试了以下方法。

mydict = {'File1': 'some text. \n Foo extract this. \n Bar extract this', 
'File2': 'more text. \n Bar extract this too.'}
mywords = ['Foo', 'Bar']
mylist= []
for k,v in mydict.items():
        for word in mywords:
            extracted = (re.findall('^ ' + word + ".*", v, flags=re.IGNORECASE|re.MULTILINE))
            mylist.append(extracted[:1])

这给了我

[[' Foo extract this. '],
 [' Bar extract this'],
 [],
 [' Bar extract this too.']]

但是,我希望每次在文件中搜索单词时输出都有 2 个嵌套列表(对于每个文件),而不是一个单独的列表。

期望的输出:

[[' Foo extract this. '], [' Bar extract this']],
 [[], [' Bar extract this too.']]

您可能想尝试制作子列表并将它们附加到您的列表中。 这是一个可能的解决方案:

mydict = {'File1': 'some text. \n Foo extract this. \n Bar extract this', 
'File2': 'more text. \n Bar extract this too.'}
mywords = ['Foo', 'Bar']
mylist= []
for k,v in mydict.items():
    sublist = []
    for word in mywords:
        extracted = (re.findall('^ ' + word + ".*", v, flags=re.IGNORECASE|re.MULTILINE))
        sublist.append(extracted[:1])
    mylist.append(sublist)

这输出: [[[' Foo extract this. '], [' Bar extract this']], [[], [' Bar extract this too.']]] [[[' Foo extract this. '], [' Bar extract this']], [[], [' Bar extract this too.']]]


如果您想要没有周围列表的字符串,请仅在有结果时插入第一个结果:

import re

mydict = {'File1': 'some text. \n Foo extract this. \n Bar extract this', 
'File2': 'more text. \n Bar extract this too.'}
mywords = ['Foo', 'Bar']
mylist= []
for k,v in mydict.items():
    sublist = []
    for word in mywords:
        extracted = (re.findall('^ ' + word + ".*", v, flags=re.IGNORECASE|re.MULTILINE))
        if extracted: # Checks if there is at least one element in the list
            sublist.append(extracted[0])
    mylist.append(sublist)

这输出: [[' Foo extract this. ', ' Bar extract this'], [' Bar extract this too.']] [[' Foo extract this. ', ' Bar extract this'], [' Bar extract this too.']]


如果您希望能够从每个文件中获得多个结果,您可以执行以下操作(请注意,我在第二个文件中为Foo放置了另一个匹配项:

import re

mydict = {'File1': 'some text. \n Foo extract this. \n Bar extract this', 
'File2': 'more text. \n Bar extract this too. \n Bar extract this one as well'}
mywords = ['Foo', 'Bar']
mylist= []
for k,v in mydict.items():
    sublist = []
    for word in mywords:
        extracted = (re.findall('^ ' + word + ".*", v, flags=re.IGNORECASE|re.MULTILINE))
        if extracted:
            sublist += extracted
    mylist.append(sublist)

这输出: [[' Foo extract this. ', ' Bar extract this'], [' Bar extract this too. ', ' Bar extract this one as well']] [[' Foo extract this. ', ' Bar extract this'], [' Bar extract this too. ', ' Bar extract this one as well']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM