1

希望这是一个非常直截了当的问题。我有一个成绩单,我试图将其分成每个发言者的块。我目前拥有的代码是;

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']

欢迎任何建议

谢谢

4

2 回答 2

2

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']
于 2018-08-03T15:22:57.867 回答
1

非正则表达式解决方案:

['Speaker' + substr for substr in text.split('Speaker')[1:]]

输出

['Speaker 1: hello there\n\nthis is some text. \n\n',
 'Speaker 2: hello there, \n\nthis is also some text.\n']
于 2018-08-03T15:23:22.840 回答