【问题标题】:Split a string using variable pattern使用变量模式拆分字符串
【发布时间】:2021-09-07 23:48:50
【问题描述】:

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

我们将不胜感激。

【问题讨论】:

  • 我强烈推荐在这里使用 HTML 解析器。可以使用beautifulsoup 模块吗?

标签: python html string split


【解决方案1】:

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

【讨论】:

  • 非常感谢!!!完美的答案 - 简短且解释清楚。
猜你喜欢
  • 1970-01-01
  • 2012-08-17
  • 2015-08-30
  • 2014-10-14
  • 2015-11-30
  • 1970-01-01
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多