批量将B站bcc格式的视频字幕转换为srt格式的视频字幕

在B站下载的视频对应的bcc格式字幕,在potplayer中不能播放,

以下代码中输入文件夹的路径,就可以批量把json文件转换为srt文件,存放在当前文件夹下的名为srt的子文件夹下。

 

 1 # -- coding: utf-8 --
 2 import math
 3 import os
 4 
 5 #单个bbc文件转换为srt文件
 6 def bcc2srt(datas, srt_file_name, srt_file_path):
 7     srt_file = ''
 8     i = 1
 9     for data in datas:
10         start = data['from']  # 获取开始时间
11         stop = data['to']  # 获取结束时间
12         content = data['content']  # 获取字幕内容
13         srt_file += '{}\n'.format(i)  # 加入序号
14         hour = math.floor(start) // 3600
15         minute = (math.floor(start) - hour * 3600) // 60
16         sec = math.floor(start) - hour * 3600 - minute * 60
17         minisec = int(math.modf(start)[0] * 100)  # 处理开始时间
18         srt_file += str(hour).zfill(2) + ':' + str(minute).zfill(2) + ':' + str(sec).zfill(2) + ',' + str(minisec).zfill(2)  # 将数字填充0并按照格式写入
19         srt_file += ' --> '
20         hour = math.floor(stop) // 3600
21         minute = (math.floor(stop) - hour * 3600) // 60
22         sec = math.floor(stop) - hour * 3600 - minute * 60
23         minisec = abs(int(math.modf(stop)[0] * 100 - 1))  # 此处减1是为了防止两个字幕同时出现
24         srt_file += str(hour).zfill(2) + ':' + str(minute).zfill(2) + ':' + str(sec).zfill(2) + ',' + str(minisec).zfill(2)
25         srt_file += '\n' + content + '\n\n'  # 加入字幕文字
26         i += 1
27     with open(os.path.join(srt_file_path, srt_file_name), 'w', encoding='utf-8') as f:
28         f.write(srt_file) 
29 
30 
31 #批量转换bcc文件为srt文件
32 def convert_bcc_to_srt(file_path):
33     files = os.listdir(file_path) #当前路径下原始文件
34     #print(files)
35     
36     #提取当前路径下bcc格式文件的文件名
37     bcc_file = []
38     for file in files:
39         if file[-4:] == ".bcc":
40             bcc_file.append(file)      
41     #print(bcc_file)
42     
43     #在当前文件夹下创建存放srt格式文件的子文件夹
44     srt_file_path = os.path.join(file_path, 'srt') #更改后缀后字幕文件的路径    
45     isExists = os.path.exists(srt_file_path)
46     if not isExists:
47         os.mkdir(srt_file_path)
48         
49     #读取每个bcc文件的内容    
50     for fli in bcc_file:
51         file_name = fli.replace(fli[-4:], '.srt') #更改文件名称
52         with open(os.path.join(file_path, fli), encoding='utf-8') as f:
53             datas = f.read()
54             datas = eval(datas) #将str格式的内容转换成dict格式
55             bcc2srt(datas["body"], file_name, srt_file_path)
56             f.close()
57             #print(datas)    
58     
59 
60 if __name__ == '__main__':   
61     folder_path = 'D:\\1111' #bcc字幕文件的路径(注意路径的格式)
62     convert_bcc_to_srt(folder_path)

 

posted @ 2020-08-18 18:59  WWBlog  阅读(1865)  评论(0编辑  收藏  举报