python - 正则表达式:括号内子字符串的条件匹配
问题描述
我有一个来自直播电视片段的文本语料库,我正在尝试找到一种方法来删除对预录片段或使用正则表达式的广告插播的引用。考虑以下我正在使用的文本类型的示例脚本:
myconvo = "speaker1: hello
speaker2: hello (clears throat), let me show you something Ted Cruz said last week
(begin audio clip)
Ted Cruz (R-TX): My dad did not shoot JFK, why do people keep saying that?
(end audio clip)
speaker1: now isn't that interesting"
语料库是从不同的来源产生的,具有不同的标准(例如,一些使用括号,另一些使用括号)。但是,以上是广义的表示。为了解决这个问题,我写了以下内容:
cleanString = re.sub(r"\n[\(\[].+[\)\]]\n*[\.a-zA-Z\s\d,'’:;!?@£$\"“”-]*\n*[\(\[].+[\)\]]", '', myconvo)
为清楚起见,编写此脚本是为了执行以下操作:
1.寻找换行符,后跟左/右括号/括号,中间有文本(其中文本表示段的开头\n[\(\[.+][\)\]]
2.查找任意数量的换行符,后跟与要删除的段相对应的文本\n*[\.a-zA-Z\s\d,'’:;!?@£$\"“”-]*
3.寻找一个换行符,后跟包含要删除段结尾的括号/括号
4.用空格替换
这适用于要删除的文本不包含括号的情况。但是,如果确实如此,它会完全与输出混淆(这和我所拥有的其他一些)。
我想知道是否有一种方法可以指定仅在行首应用的文本,但我不确定如何去做。我还要指出,这是我第一个接近这个长度的正则表达式,所以如果有人有更好的解决方法,我非常欢迎输入。
编辑:为了清楚起见,我希望最终得到的是:
myconvo = "speaker1: hello
speaker2: hello (clears throat), let me show you something Ted Cruz said last week
speaker1: now isn't that interesting"
解决方案
你可以试试:
import re
myconvo = """speaker1: hello
speaker2: hello (clears throat), let me show you something Ted Cruz said last week
(begin audio clip)
Ted Cruz (R-TX): My dad did not shoot JFK, why do people keep saying that?
(end audio clip)
speaker1: now isn't that interesting"""
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
myconvo = myconvo[0:match.start()] + myconvo[match.end():]
print(myconvo)
给出输出
speaker1: hello
speaker2: hello (clears throat), let me show you something Ted Cruz said (begin audio clip)
Ted Cruz (R-TX): My dad did not shoot JFK, why do people kee (end audio clip)
speaker1: now isn't that interesting
推荐阅读
- java - 在 Websphere 上运行 Project 时找不到要添加到服务器的有效父模块
- python-requests - 使用字典的预算程序
- java - 具有2个数组列表的非递归合并排序
- vba - 获取 Dymo 标签的对象名称
- javascript - Uncaught (in promise) TypeError: cannot read property graphics of undefined
- ios - (目标 C)TABLEVIEW 单元格标识符重要吗?
- python-3.x - 如何通过双击运行python代码而不自己激活virtualenv
- strapi - 如何覆盖 Strapi 管理面板端点?
- json - 将记录编组为 JSON 并返回
- authentication - Mifare Desfire EV1:了解认证过程命令