在列表中提到某些关键字后对字符串进行切片

Dyl*_*nny 5 python string list

我是 python 的新手,我遇到了一个问题。我想要做的是我有一个包含两个人之间对话的字符串:

str = "  dylankid: *random words* senpai: *random words* dylankid: *random words* senpai: *random words*"
Run Code Online (Sandbox Code Playgroud)

我想使用 dylankid 和 senpai 作为名称从字符串创建 2 个列表:

dylankid = [ ]
senpai = [ ]
Run Code Online (Sandbox Code Playgroud)

这就是我苦苦挣扎的地方,在列表 dylankid 中,我想将所有出现在 'dylankid' 之后的单词放在字符串中,但在下一个 'dylankid' 或 'senpai' 之前,同样适用于 senpai 列表,所以它看起来像这样

dylankid = ["random words", "random words", "random words"]
senpai = ["random words", "random words", "random words"]    
Run Code Online (Sandbox Code Playgroud)

dylankid 包含来自 dylankid 的所有消息,反之亦然。

我已经研究过切片并使用split()and re.compile(),但我想不出一种方法来指定开始切片和停止的位置。

希望它足够清楚,任何帮助将不胜感激:)

nie*_*mmi 5

以下代码将创建一个字典,其中键是人,值是消息列表:

from collections import defaultdict
import re

PATTERN = '''
    \s*                         # Any amount of space
    (dylankid|senpai)           # Capture person
    :\s                         # Colon and single space
    (.*?)                       # Capture everything, non-greedy
    (?=\sdylankid:|\ssenpai:|$) # Until we find following person or end of string
'''
s = "  dylankid: *random words* senpai: *random words* dylankid: *random words* senpai: *random words*"
res = defaultdict(list)
for person, message in re.findall(PATTERN, s, re.VERBOSE):
    res[person].append(message)

print res['dylankid']
print res['senpai']
Run Code Online (Sandbox Code Playgroud)

它将产生以下输出:

['*random words*', '*random words*']
['*random words*', '*random words*']
Run Code Online (Sandbox Code Playgroud)