批量將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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM