How can I convert this data to save the subtitle?
data={"tt0064621":
{"title": "Name of movie - 1971",
"subtitle": "b'1\\n00:00:40,916 --> 00:00:46,346\\n\\xe2\\x99\\xaa A"
"\\B \\xe2\\x99\\xaa\\n\\n2\\n00:00:47,381 --> 00:00:50,174"
"\\n\\xe2\\x99\\xaa It\\'s C \\xe2\\x99\\xaa\\n\\n3\\n00:00:50,175 -->'"}}
sub_create= data["tt0064621"]['subtitle']
saved_file_name = "subtitle.srt"
with open(saved_file_name, 'wb') as f:
f.write(sub_create) #sub_create.encode() Doesn't work
Since what's in your subtitle
field is Python code, you can just call eval
on it. Here's a version of your code updated to do that:
import ast
data={"tt0064621":
{"title": "Name of movie - 1971",
"subtitle": "b'1\\n00:00:40,916 --> 00:00:46,346\\n\\xe2\\x99\\xaa A"
"\\B \\xe2\\x99\\xaa\\n\\n2\\n00:00:47,381 --> 00:00:50,174"
"\\n\\xe2\\x99\\xaa It\\'s C \\xe2\\x99\\xaa\\n\\n3\\n00:00:50,175 -->'"}}
sub_create= ast.literal_eval(data["tt0064621"]['subtitle']) # <-- added call to
saved_file_name = "/tmp/subtitle.srt"
with open(saved_file_name, 'wb') as f:
f.write(sub_create) #sub_create.encode() Doesn't work
Resulting contents of '/tmp/subtitle.srt':
1
00:00:40,916 --> 00:00:46,346
♪ A\B ♪
2
00:00:47,381 --> 00:00:50,174
♪ It's C ♪
3
00:00:50,175 -->
This is a kinda strange thing to have to do, but if you can't change the format of your data, then this seems like a good way to go about the problem. It would be better if you could change your data to not have Python code embedded in it (or something else that looks like a Python byte array constant).
UPDATE: Please heed @kaya3's warning about worrying about where this data might be coming from and so the risk of running a full eval
on it, I've changed the code per their suggestion to use a safer alternative, ast.literal_eval
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.