首页 > 解决方案 > 如何将base64解码从python2转换为python3

问题描述

我正在开发一个下载和处理字幕文件的脚本。文件以 gzip 格式出现,文档说:使用:gzinflate(substr(base64_decode($subs_b64_data_from_xmlrpc),10))。在 Python 2 中这很好用,我最终得到一个包含字幕文本的 str 。

compressed_data = download_data['data'][0]['data'].decode('base64')
sub_text = gzip.GzipFile(fileobj=io.BytesIO(compressed_data)).read()
print(sub_text)

给我这个str:

841
01:52:28,344 --> 01:52:29,878
Sweet dreams, angel.

842
01:53:44,844 --> 01:53:46,377
I love you, honey.

当我使用 python 3 时,我根据 python 3 文档将 .decode('base64') 更改为 base64.b64decode() 。

compressed_data = base64.b64decode(download_data['data'][0]['data'])
sub_text = gzip.GzipFile(fileobj=io.BytesIO(compressed_data)).read()
print(sub_text)

但现在我的数据最终成为一个字节对象,打印的数据如下所示:

00:33:30,009\r\ncalled Babies I\r\nDon\'t Care About.\r\n\r\n694\r\n00:33:31,305 --> 00:34:31,557\r\n

我怎样才能在 python3 中正确地做到这一点,所以我最终也会得到一个 str ?

标签: pythonpython-3.xbase64

解决方案


如果 sub_text 以字节为单位,你应该试试这个......

print(sub_text.decode('utf-8'))

推荐阅读