Python - 根据 2 个关键字拆分具有长字符串的列表

Python - Split a list with a long string based on 2 keywords

我有一个包含长字符串的列表。如何拆分字符串以提取从 'MyKeyword' 到 'My Data' 的部分。这些词在我的列表中多次出现,所以我想以此为基础拆分它,并尽可能包括 MyKeyword 和 MyData

当前数据示例:

['MyKeyword This is my data MyData. MyKeyword and chunk of text here. Random text. MyData is this etc etc ']

期望的输出:

['MyKeyword This is my data', 'MyData.', 'MyKeyword and chunk of text here. Random text.','MyData is this etc etc ']

当前代码:


from itertools import groupby
#linelist = ["a", "b", "", "c", "d", "e", "", "a"]
split_at = "MyKeyword"
[list(g) for k, g in groupby(output2, lambda x: x != split_at) if k]

您可以使用正则表达式,以惰性模式匹配从MyKeywordMyData的所有文本:

>>> import re
>>> re.findall("MyKeyword.*?MyData\.?","MyKeyword This is my data, MyData. MyKeyword and chunk of text here. Random text. MyData is this etc etc ")
['MyKeyword This is my data, MyData.', 'MyKeyword and chunk of text here. Random text. MyData']
  • .*?表示0到无限个字符,但是在惰性模式下(*?),即越少越好;
  • \.?表示可选句号

EDIT(根据新要求):

您需要的正则表达式类似于

MyKeyword.*?(?= ?MyData|$)|MyData.*?(?= ?MyKeyword|$)

它从匹配MyKeyword(resp. MyData)的点开始,然后像上面一样捕获尽可能少的字符,直到到达MyData( resp. MyKeyword) 或字符串结尾。

确实:

  • | 是一个特殊字符,表示“或”
  • $匹配字符串结尾
  • ? 是可选的 space
  • (?=<expr>) 称为正向超前,意思是“后跟 <expr>