python用正则获取字幕中的文本

本文介绍如何使用Python通过正则表达式从srt、ass等字幕文件中提取文本内容。通过分析字幕文件的格式,使用findall()匹配序号、时间线和字幕文本,并处理中英双字幕的情况,最终得到一个包含中英文字幕对应关系的列表。
摘要由CSDN通过智能技术生成

首先去字幕库或字幕网站得到字幕文件,格式一般为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(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值