1

Hopefully this is a pretty straight-forward question. I have a transcript that i am trying to split into chunks of each speaker. The code I currently have is;

text = '''
Speaker 1: hello there

this is some text. 

Speaker 2: hello there, 

this is also some text.
'''

a = text.split('\nSpeaker')

This splits the text as i would want it to, however I miss the 'Speaker' identifier from the second utterance. I would need to keep this for identification purposes. Specifically, what i am trying to obtain is a result akin to the following;

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

Any suggestions are welcome

Thanks

cookie1986
  • 865
  • 12
  • 27

2 Answers2

2

re.split in multiline mode, matching \n (newline), with a zero-width positive lookahead to match Speaker ((?=Speaker)):

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

Example:

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']
heemayl
  • 39,294
  • 7
  • 70
  • 76
1

non-regex solution:

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

output

['Speaker 1: hello there\n\nthis is some text. \n\n',
 'Speaker 2: hello there, \n\nthis is also some text.\n']
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47