make python codes that takes a json file with this format: { "font\size": 0.4,…
- User
make python codes that takes a json file with this format:
{ "font_size": 0.4, "font_color": "#FFFFFF", "background_alpha": 0.5, "background_color": "#9C27B0", "Stroke": "none", "body": [ { "from": 0.867, "to": 3, "location": 2, "content": "(The start of the project, April 2022)" }, { "from": 3.333, "to": 5.767, "location": 2, "content": "(A technical meeting\nwith dozens of specialists)" } }
and convert into an srt file named "reverse_ep11_subs.srt"
- Assistant
Here's the Python code that takes a JSON file with the specified format and converts it into an SRT file:
pythonimport json def format_time(seconds): minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) return "{:02d}:{:02d}:{:02d},{:03d}".format(hours, minutes, seconds, int(seconds * 1000) % 1000) with open('input.json', 'r') as f: data = json.load(f) with open('reverse_ep11_subs.srt', 'w') as f: index = 1 for item in data['body']: f.write(str(index) + '\n') f.write(format_time(item['from']) + ' --> ' + format_time(item['to']) + '\n') f.write(item['content'] + '\n\n') index += 1This code reads the input JSON file named "input.json", converts the "from" and "to" time values into the SRT format, and writes the resulting SRT file named "reverse_ep11_subs.srt".
- User
I'm getting this error: ValueError: Unknown format code 'd' for object of type 'float' on this line: return "{:02d}:{:02d}:{:02d},{:03d}".format(hours, minutes, seconds, int(seconds * 1000) % 1000)
- Assistant
I apologize for the error. The issue is that the format code 'd' is for integer values, not float values, which causes the ValueError. Here's an updated version of the code that converts the float values into integers before formatting them:
pythonimport json def format_time(seconds): minutes, seconds = divmod(int(seconds), 60) hours, minutes = divmod(minutes, 60) return "{:02d}:{:02d}:{:02d},{:03d}".format(hours, minutes, seconds, int(seconds * 1000) % 1000) with open('input.json', 'r') as f: data = json.load(f) with open('reverse_ep11_subs.srt', 'w') as f: index = 1 for item in data['body']: f.write(str(index) + '\n') f.write(format_time(item['from']) + ' --> ' + format_time(item['to']) + '\n') f.write(item['content'] + '\n\n') index += 1This version of the code should work properly and avoid the ValueError.