使用Python把json字幕转换成srt字幕

在B站下载了json格式字幕,potplayer不支持这种格式,于是用python写了个小工具,转成了srt格式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import math,json
 
def zimu(jsonpath, srtpath):
    file = ''  # 这个变量用来保存数据
    i = 1
    with open(jsonpath, 'r', encoding='utf-8') as f:
        datas = json.load(f)  # 加载文件数据
    subs = datas.get('body')
    for data in subs:
        start = data['from'# 获取开始时间
        stop = data['to'# 获取结束时间
        content = data['content'# 获取字幕内容
        file += '{}\n'.format(i)  # 加入序号
        hour = math.floor(start) // 3600
        minute = (math.floor(start) - hour * 3600) // 60
        sec = math.floor(start) - hour * 3600 - minute * 60
        minisec = int(math.modf(start)[0] * 100# 处理开始时间
        file += str(hour).zfill(2) + ':' + str(minute).zfill(2) + ':' + str(sec).zfill(2) + ',' + str(
            minisec).zfill(2# 将数字填充0并按照格式写入
        file += ' --> '
        hour = math.floor(stop) // 3600
        minute = (math.floor(stop) - hour * 3600) // 60
        sec = math.floor(stop) - hour * 3600 - minute * 60
        minisec = abs(int(math.modf(stop)[0] * 100 - 1))  # 此处减1是为了防止两个字幕同时出现
        file += str(hour).zfill(2) + ':' + str(minute).zfill(2) + ':' + str(sec).zfill(2) + ',' + str(
            minisec).zfill(2)
        file += '\n' + content + '\n\n'  # 加入字幕文字
        i += 1
    with open(srtpath, 'w+', encoding='utf-8') as fp:
        fp.write(file# 将数据写入文件
 
 
def main():
    #json文件所在位置
    jsonpath = r'C:\mulu.json'
    #srt生成位置   
    srtpath = r'C:\mulu.srt'
 
 
    zimu(jsonpath, srtpath)
 
 
if __name__ == '__main__':
    main()
  

 

posted @   studieren  阅读(721)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示