【发布时间】:2020-07-01 21:47:27
【问题描述】:
我有一个字典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 项的列表?
标签: python list loops dictionary for-loop