Python - перебирая список и словарь для получения вывода вложенного списка - PullRequest
2 голосов
/ 20 марта 2020

У меня есть словарь 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.']]

1 Ответ

1 голос
/ 20 марта 2020

Возможно, вы захотите создать подсписки и добавить их в свой список. Вот возможное решение:

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.']]]


Если вы хотите, чтобы строки были без окружающего списка, вставляйте первый результат только при наличии результат:

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 во втором файле:

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

...