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.']]
しかし、私は、出力の代わりに別のリストでは、ファイル内の単語を検索するたびに(各ファイルの)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.']]]
あなたは周囲のリストのない文字列を持っていると思った場合は、結果がある場合のみ、最初の結果を挿入します。
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']]