TypeError: a bytes-like object is required, not 'str'?

TypeError: a bytes-like object is required, not 'str'?

如何转换此数据以保存字幕?

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

由于 subtitle 字段中的内容是 Python 代码,因此您只需调用 eval 即可。这是您的代码更新版本:

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

'/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 -->

这是一件不得不做的奇怪事情,但如果您不能更改数据格式,那么这似乎是解决问题的好方法。如果您可以将数据更改为不嵌入 Python 代码(或其他看起来像 Python 字节数组常量的东西),那会更好。

更新:请注意@kaya3 关于担心这些数据可能来自何处以及 运行 完整 eval 的风险的警告,我已经根据他们的代码更改了代码建议使用更安全的替代方案 ast.literal_eval.