使用正则表达式解析.srt文件

时间:2014-05-12 23:13:54

标签: python regex srt

我在python中做了一个小脚本,但由于我很新,我陷入了一个部分: 我需要从.srt文件中获取时间和文本。例如,来自

1
00:00:01,000 --> 00:00:04,074
Subtitles downloaded from www.OpenSubtitles.org

我需要得到:

00:00:01,000 --> 00:00:04,074

Subtitles downloaded from www.OpenSubtitles.org

我已经设法制作了正时的正则表达式,但我被困在文本中。我已经尝试使用后面的我使用正则表达式进行计时:

( ?<=(\d+):(\d+):(\d+)(?:\,)(\d+) --> (\d+):(\d+):(\d+)(?:\,)(\d+) )\w+

但没有效果。就个人而言,我认为使用后面的是解决这个问题的正确方法,但我不确定如何正确编写它。谁能帮我?感谢。

5 个答案:

答案 0 :(得分:12)

老实说,我认为没有任何理由让正则表达式解决这个问题。 .srt个文件为highly structured。结构如下:

  • 从1开始的整数,单调递增
  • 开始 - &gt;停止计时
  • 一行或更多字幕内容
  • 一个空行

...并重复一遍。请注意粗体部分 - 您可能必须在时间码之后捕获1,2或20行字幕内容。

所以,只需利用结构。通过这种方式,您可以一次解析所有内容,而无需一次将多行放入内存中,并且仍然可以将每个字幕的所有信息保存在一起。

from itertools import groupby
# "chunk" our input file, delimited by blank lines
with open(filename) as f:
    res = [list(g) for b,g in groupby(f, lambda x: bool(x.strip())) if b]

例如,使用SRT文档页面上的示例,我得到:

res
Out[60]: 
[['1\n',
  '00:02:17,440 --> 00:02:20,375\n',
  "Senator, we're making\n",
  'our final approach into Coruscant.\n'],
 ['2\n', '00:02:20,476 --> 00:02:22,501\n', 'Very good, Lieutenant.\n']]

我可以进一步将其转换为有意义的对象列表:

from collections import namedtuple

Subtitle = namedtuple('Subtitle', 'number start end content')

subs = []

for sub in res:
    if len(sub) >= 3: # not strictly necessary, but better safe than sorry
        sub = [x.strip() for x in sub]
        number, start_end, *content = sub # py3 syntax
        start, end = start_end.split(' --> ')
        subs.append(Subtitle(number, start, end, content))

subs
Out[65]: 
[Subtitle(number='1', start='00:02:17,440', end='00:02:20,375', content=["Senator, we're making", 'our final approach into Coruscant.']),
 Subtitle(number='2', start='00:02:20,476', end='00:02:22,501', content=['Very good, Lieutenant.'])]

答案 1 :(得分:1)

不同意@roippi。正则表达式是文本匹配的一个非常好的解决方案。而这个解决方案的正则表达式并不棘手。

import re   

f = file.open(yoursrtfile)
# Parse the file content
content = f.read()
# Find all result in content
# The first big (__) retrieve the timing, \s+ match all timing in between,
# The (.+) means retrieve any text content after that.
result = re.findall("(\d+:\d+:\d+,\d+ --> \d+:\d+:\d+,\d+)\s+(.+)", content)
# Just print out the result list. I recommend you do some formatting here.
print result

答案 2 :(得分:1)

号:^[0-9]+$
时间:
^[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9][0-9][0-9] --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9][0-9][0-9]$
字符串:*[a-zA-Z]+*

希望这有帮助。

答案 3 :(得分:1)

感谢@roippi这个优秀的解析器。 在不到40行中编写srt到stl转换器帮助我很多(虽然在python2中,因为它必须适合更大的项目)

from __future__ import print_function, division
from itertools import groupby
from collections import namedtuple

# prepare  - adapt to you needs or use sys.argv
inputname = 'FR.srt'  
outputname = 'FR.stl'
stlheader = """
$FontName           = Arial
$FontSize           = 34
$HorzAlign          = Center
$VertAlign          = Bottom

"""
def converttime(sttime):
    "convert from srt time format (0...999) to stl one (0...25)"
    st = sttime.split(',')
    return "%s:%02d"%(st[0], round(25*float(st[1])  /1000))

# load
with open(inputname,'r') as f:
    res = [list(g) for b,g in groupby(f, lambda x: bool(x.strip())) if b]

# parse
Subtitle = namedtuple('Subtitle', 'number start end content')
subs = []
for sub in res:
    if len(sub) >= 3: # not strictly necessary, but better safe than sorry
        sub = [x.strip() for x in sub]
        number, start_end, content = sub[0], sub[1], sub[2:]   # py 2 syntax
        start, end = start_end.split(' --> ')
        subs.append(Subtitle(number, start, end, content))

# write
with open(outputname,'w') as F:
    F.write(stlheader)
    for sub in subs:
        F.write("%s , %s , %s\n"%(converttime(sub.start), converttime(sub.end), "|".join(sub.content)) )

答案 4 :(得分:0)

时间:

pattern = ("(\d{2}:\d{2}:\d{2},\d{3}?.*)")