파이썬 - 목록과 사전을 반복하는 것은 중첩 된 목록 출력을 얻을 수 있습니다

desmonwu2001 :

나는 사전이 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.']]

그러나, 나는 출력 대신 별도의 목록이 파일에서 단어를 검색 할 때마다의 (각 파일에 대한)이 중첩 된 목록을 갖고 싶어.

원하는 출력 :

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


당신이 주변 목록이없는 문자열을 가지고 싶었다면 결과가있는 경우에만, 첫 번째 결과를 삽입 :

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

추천

출처http://43.154.161.224:23101/article/api/json?id=351790&siteId=1