Tengo un diccionario mydict
que contiene algunos nombres de archivo como llaves y el texto dentro de ellos como valores.
Estoy extracción de una lista de palabras del texto en cada archivo. Las palabras se almacenan en una lista mywords
.
He probado lo siguiente.
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])
Esto me da
[[' Foo extract this. '],
[' Bar extract this'],
[],
[' Bar extract this too.']]
Sin embargo, quiero que la salida tiene 2 listas anidadas (por cada archivo) en lugar de una lista separada cada vez que se busca una palabra en un archivo.
Salida deseada:
[[' Foo extract this. '], [' Bar extract this']],
[[], [' Bar extract this too.']]
Es posible que desee intentar hacer sublistas y añadiéndolos a su lista en su lugar. He aquí una posible solución:
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)
Este salidas: [[[' Foo extract this. '], [' Bar extract this']], [[], [' Bar extract this too.']]]
Si quería tener las cuerdas sin que la enumeración que rodea, inserte el primer resultado sólo si hay un resultado:
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)
Este salidas: [[' Foo extract this. ', ' Bar extract this'], [' Bar extract this too.']]
Si usted quiere ser capaz de obtener varios resultados de cada archivo, puede hacerlo de la siguiente manera (nota que puse otro partido para Foo
en el segundo archivo:
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)
Este salidas: [[' Foo extract this. ', ' Bar extract this'], [' Bar extract this too. ', ' Bar extract this one as well']]