首先去字幕库或字幕网站得到字幕文件,格式一般为srt、ass、Webvtt、STL等,将格式修改为后缀txt文件,可以在python中读取。
打开字幕观察它的格式,一般为序号,时间线,字幕文本,回车。使用正则表达式中的findall()函数,应用.*贪婪模式匹配所有的字幕文本,从而舍弃不需要的时间线和序号。
如纯英文字幕格式:
1
00:00:48,422 --> 00:00:53,177
Once upon a time there was a lovely princess.
2
00:00:53,427 --> 00:01:02,019
But she had an enchantment upon her of a fearful sort,
which could only be broken by Love's first kiss.
3
00:01:02,270 --> 00:01:08,609
She was locked away in a castle guarded by a terrible
fire breathing dragon.
4
00:01:08,860 --> 00:01:15,992
Many brave knights had attempted to free her from
this dreadful prison, but none prevailed.
5
00:01:16,242 --> 00:01:23,040
She waited in the dragon's keep in the highest
room of the tallest tower for her true love
6
00:01:23,291 --> 00:01:27,253
and true love's first kiss.
7
00:01:27,503 --> 00:01:29,714
Like that's ever going to happen.
8
00:01:29,964 --> 00:01:34,552
What a loony.
9
00:01:51,485 --> 00:01:57,658
Shrek
\d+\n是第一行的序号,.?–>.?,\d{3} 是第二行的时间线,最后是逗号加三个毫秒数字,
字幕文本有时是一行,有时是两行,所以使用 (.[\n]?.) , ?表示零次或一次,即零次是一行字幕,一次是两行文本。
第四行是空行 \s*\n
file = open('Shrek.txt', 'r')
try:
while True:
text_line = file.read(