python - 如何使用 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']]
解决方案
您可以使用
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']]
正则表达式详细信息
^
- 行首(由于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.*
- 线路的其余部分。
推荐阅读
- python - 使用 Quantized MobilenetV1 Tf-lite 预测期间不同图像的相同输出
- c++ - c++参考错误
- c++ - 无法解决PCL气缸检测导致的错误
- typescript - 回家 Object.assign 可以将对象的副本发送到函数,而扩展运算符不可以吗?
- ios - 如何在 swift 中以编程方式在 Gallery 中创建文件夹?
- postgresql - 如何使用 Postgresql 在 Postgis 中将不相交的多边形合并为单个多边形
- ios - 从 SwiftUI 中的 NavigationBarItem 菜单显示不同的视图
- amazon-web-services - 如何通过 cloudformation 在 lambda 中添加数据库代理?
- airflow - 安装在远程 centos 服务器上的 Apache AirFlow 无法从本地访问
- javascript - 即使未填写必填字段,我是否可以在超时时提交表单