【问题标题】:splitting a subtitle text with re.split() [duplicate]用 re.split() 分割字幕文本 [重复]
【发布时间】:2021-03-05 08:33:24
【问题描述】:

我正在尝试拆分以下字符串

sub_text = """278
00:15:13,442 --> 00:15:14,436
Mr. Burns,

279
00:15:14,454 --> 00:15:17,893
I came here because my brother
is about to be wrongfully convicted,

280
00:15:17,947 --> 00:15:19,514
and the man I'm looking for

281
00:15:19,542 --> 00:15:21,010
would help me find the truth. 
"""

进入这样的列表

[('00:15:13,442 --> 00:15:14,436', 'Mr. Burns,'), ('00:15:14,454 --> 00:15:17,893', 'I came here because my brother is about to be wrongfully convicted,'), ...].

我正在尝试使用 regex 拆分文本,但它不起作用。

re.split(r'^\d+$\n', sub_text) 返回一个完整的字符串,即使一切似乎都匹配得很好 here

【问题讨论】:

  • 正则表达式不起作用,因为您没有使用多行标志。但为什么不直接做:sub_text.split('\n\n')

标签: python regex string list split


【解决方案1】:

你可以使用正则表达式:

>>> import re
>>> re.findall(r"(\d+:\d+:\d+,\d+ --> \d+:\d+:\d+,\d+)\n(.+(?:\n.+)?)\n", sub_text)
[('00:15:13,442 --> 00:15:14,436', 'Mr. Burns,'), 
 ('00:15:14,454 --> 00:15:17,893', 'I came here because my brother\nis about to be wrongfully convicted,'), 
 ('00:15:17,947 --> 00:15:19,514', "and the man I'm looking for"), 
 ('00:15:19,542 --> 00:15:21,010', 'would help me find the truth. ')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2016-02-14
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多