首页 > 解决方案 > 如何使用 re.split 在成绩单中分离说话者和语音?

问题描述

我正在处理文本转录本,并试图找到一种方法将演讲者的姓名与他们的演讲内容分开。我一直在尝试使用 re.split 但到目前为止还没有运气。

dummyText1 = "bill: hello \nted: hello \nto you \nbill: goodbye \nted: goodbye \nto you"

-------------------
Original Transcript
-------------------
(L1)  bill: hello
(L2)  ted:  hello 
(L3)        to you
(L4)  bill: goodbye
(L5)  ted:  goodbye 
(L6)        to you

----------------
Desired Output
-------------------------
Speaker | Speech
-------------------------
bill    | hello
ted     | hello to you
bill    | goodbye
ted     | goodbye to you

我最初的想法是对换行符+单词使用积极的前瞻组合,并使用“:”符号来标记语音的开始,但这不起作用。我也不确定如何将共享同一说话者的行分组(即,将第 2-3 行和第 5-6 行处理为单个语音轮而不是单独的行)。

splitText1 = re.split(r"(\n?=[a-z])*:", dummyText1, flags=re.MULTILINE) 

我的预期输出将是一个列表对象列表,每个嵌套列表都包含语音 ID 和语音(作为字符串)。

desired_output = [['bill','hello'],['ted','hello to you'],['bill','goodbye'],['ted','goodbye to you']]

标签: pythonregex

解决方案


您可以使用

import re
dummyText1 = "bill: hello \nted: hello \nto you \nbill: goodbye \nted: goodbye \nto you"
p = r'^((?:[^\W\d_]|[^\S\r\n])+):(.*(?:\n(?!(?:[^\W\d_]|[^\S\r\n])+:).*)*)'
print( [[x.strip(),y.replace('\n','').strip()] for x,y in re.findall(p, dummyText1, re.M)])

输出:

[['bill', 'hello'], ['ted', 'hello to you'], ['bill', 'goodbye'], ['ted', 'goodbye to you']]

请参阅Python 演示正则表达式演示

正则表达式详细信息

  • ^- 行首(由于re.M,^也匹配换行后的位置)
  • ((?:[^\W\d_]|[^\S\r\n])+)- 第 1 组:一个或多个字母 ( [^\W\d_]) 或 ( |) 水平空格 ( [^\S\r\n])
  • :- 一个冒号
  • (.*(?:\n(?!(?:[^\W\d_]|[^\S\r\n])+:).*)*)- 第 2 组:
    • .*- 线路的其余部分
    • (?:\n(?!(?:[^\W\d_]|[^\S\r\n])+:).*)*- 零次或多次出现
      • \n(?!(?:[^\W\d_]|[^\S\r\n])+:)- 换行符后不紧跟 1 个或多个字母或水平空格,然后是:char
      • .*- 线路的其余部分。

推荐阅读