首页 > 解决方案 > 使用变量模式拆分字符串

问题描述

我需要从 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>']

任何帮助将不胜感激。

标签: pythonhtmlstringsplit

解决方案


正如上面的评论所暗示的,你可能想在这里使用 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

推荐阅读