希望这是一个非常简单的问题。我有一个抄本,试图将每个发言人分成几部分。我目前拥有的代码是;

text = '''
Speaker 1: hello there

this is some text.

Speaker 2: hello there,

this is also some text.
'''

a = text.split('\nSpeaker')


这将按我希望的方式拆分文本,但是我错过了第二个发音中的“扬声器”标识符。我需要保留此信息以用于识别。具体来说,我试图获得的结果类似于以下内容;

['Speaker 1: hello there\n\nI am checking to see if this works. \n', ' Speaker2:
Hopefully it will, \n\nit seems pretty straightforward.\n']


欢迎任何建议

谢谢

最佳答案

在多行模式下的re.split,匹配\n(换行符),且零宽度正向超前匹配以匹配Speaker(?=Speaker)):

re.split(r'\n(?=Speaker)', text, flags=re.MULTILINE)


例:

In [228]: text = '''Speaker 1: hello there
     ...:
     ...: this is some text.
     ...:
     ...: Speaker 2: hello there,
     ...:
     ...: this is also some text.
     ...: '''

In [229]: re.split(r'\n(?=Speaker)', text, flags=re.MULTILINE)
Out[229]:
['Speaker 1: hello there\n\nthis is some text. \n',
 'Speaker 2: hello there, \n\nthis is also some text.\n']

10-08 17:03