本帖最后由 felixzhao1111 于 2021-12-25 21:14 编辑
目前仅支持Windows平台2.5.1以及之前版本的剪映
主要功能是可以配合剪映的识别字幕功能
将剪映最后一次打开的项目中的字幕转换为srt字幕并保存
[Python] 纯文本查看 复制代码 # -*- coding: utf-8 -*-
"""
本程序基于Python3编写,已适配2.5.1版本剪映
"""
from getpass import getuser
from os import path, walk
from json import load
from re import compile
# 自定义srt字幕的保存路径包括文件名
SAVE_FILE_PATH = '剪映提取字幕.srt'
def _formatting_time(time_int):
# 使用正则表达式处理时间格式化问题
if time_int == 0:
return '00:00:00,000'
p = compile(r'(\d*)(\d{3})\d{3}')
res = p.findall(str(time_int))[0]
if res[0] == '':
hms = '00:00:00'
else:
h = 0
m = 0
s = int(res[0])
while s >= 60:
m += 1
s -= 60
while m >= 60:
h += 1
m -= 60
while h >= 24:
exit('暂不支持超过24小时的字幕文件转换')
hms = ':'.join((str(h).zfill(2), str(m).zfill(2), str(s).zfill(2)))
return ','.join((hms, res[1]))
def formatting_time(start, end):
# 拼接时间格式化后的字符串
return ' --> '.join((_formatting_time(start), _formatting_time(end)))
def main():
# 取得电脑的用户名,用来获取剪映缓存文件夹的绝对路径
username = getuser()
# 拼接出剪映缓存文件夹的绝对路径
jy_cache_path = f'C:/Users/{username}/AppData/Local/JianyingPro/User Data/Projects/com.lveditor.draft'
# 拿到最后一次打开的项目文件信息(内含字幕信息)
info_file_path = ''
if path.exists(jy_cache_path):
tup = walk(jy_cache_path)
for dirpath, dirnames, filenames in tup:
if 'root_meta_info.json' in filenames:
info_file_path = f'{jy_cache_path}/root_meta_info.json'
elif 'root_draft_meta_info.json' in filenames:
info_file_path = f'{jy_cache_path}/root_draft_meta_info.json'
if info_file_path:
with open(info_file_path, 'r', encoding='utf-8') as f:
sub_file_path = (load(f)['all_draft_store'][0]['draft_fold_path'])
# 打开json文件并将其转换为srt文件
if path.exists(sub_file_path):
with open(f'{sub_file_path}/draft_content.json', 'r', encoding='utf-8') as f:
sub_file_json = load(f)
time_list = []
content_list = []
for i in sub_file_json['tracks'][1]['segments']:
start_time = int(i['target_timerange']['start'])
end_time = int(i['target_timerange']['start'] + i['target_timerange']['duration'])
time_list.append(formatting_time(start_time, end_time))
for i in sub_file_json['materials']['texts']:
content_list.append(i['content'])
index = 0
# 保存字幕信息到文件中
with open(SAVE_FILE_PATH, 'w', encoding='utf-8') as srt:
while index < len(time_list):
srt.write(f'{index + 1}\n{time_list[index]}\n{content_list[index]}\n\n')
index += 1
if __name__ == '__main__':
main()
|