首页 > 解决方案 > 无法使用 python 解码这个字符串

问题描述

我有这个 text.ucs 文件,我正在尝试使用 python 进行解码。

file = open('text.ucs', 'r')
content = file.read()
print content

我的结果是

\xf\xe\x002\22

我尝试使用 utf-16、utf-8 进行解码

content.decode('utf-16')

并得到错误

回溯(最后一次调用):文件“”,第 1 行,在文件“C:\Python27\lib\encodings\utf_16.py”中,第 16 行,在解码中返回 codecs.utf_16_decode(input, errors, True) UnicodeDecodeError: “utf16”编解码器无法解码位置 32-33 中的字节:非法编码

如果我遗漏任何东西或我的方法有误,请告诉我

编辑:已询问屏幕截图 在此处输入图像描述

标签: pythonpython-2.7

解决方案


哦,据我了解,您使用的是 python 2.xx,但编码参数仅在 python 3.xx 中添加,据我所知,我不是 python 2.xx 的大师,但您可以在谷歌中搜索 io.open 例如尝试:

file = io.open('text.usc', 'r',encoding='utf-8')
content = file.read()
print content

但是您是否需要导入 io 模块


推荐阅读