python - 使用变量模式拆分字符串
问题描述
我需要从 srt 文件中的对话框中提取标签和文本,例如:
'<b><font color="#ca6500">FEMALE VOICE:</font></b> <i>The world is changed.</i>'
我想得到:
['<b>', '<font color="#ca6500">', 'FEMALE VOICE:', '</font>', '</b>', ' ', '<i>', 'The world is changed.', '</i>']
任何帮助将不胜感激。
解决方案
正如上面的评论所暗示的,你可能想在这里使用 Beautiful Soup。话虽如此,对于只有单个嵌套的顶级 HTML 标记的文本,正则表达式可以很好地应对。这是一种re.findall
方法:
inp = '<b><font color="#ca6500">FEMALE VOICE:</font></b> <i>The world is changed.</i>'
matches = re.findall(r'<.*?>|.+?(?=<|$)', inp)
print(matches)
这打印:
['<b>', '<font color="#ca6500">', 'FEMALE VOICE:', '</font>', '</b>', ' ',
'<i>', 'The world is changed.', '</i>']
使用的正则表达式模式说:
<.*?> match an HTML tag
| OR
.+?(?=<|$) match all content until reaching either the nearest HTML tag or
the end of the input
推荐阅读
- oracle - 使用循环定义数组并添加值
- spring-cloud-stream - 如何在 SCDF httpclient(或 http-request)应用程序中使用 Kafka 标头创建 HTTP 标头?
- orocrm - Datagrid 导航链接在新选项卡中打开
- reactjs - 如何在同一个 React 无状态功能组件中同时拥有 componentWillUnmount 和 componentDidUpdate 挂钩?
- asp.net-core - 如果未通过身份验证,则重定向用户
- javascript - Nestjs 单元测试中不支持从“描述”返回 Promise
- javascript - 使用 javascript dom 在 HTML 中插入 Cite 元素
- python - 迭代列表比较类似的项目并添加来自csv Python的值
- reactjs - Formik 如何使用文件上传输入
- java - Snowflake OAuth2 如何使用还原令牌创建数据源