1. 程式人生 > 實用技巧 >批量將B站bcc格式的視訊字幕轉換為srt格式的視訊字幕

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