无法使用Python解码此字符串

2024-06-07 03:33:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个文本.ucs我试图用python解码的文件。在

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

我的结果是

\xf\xe\x002\22

我试着用utf-16,utf-8解码

^{pr2}$

然后出错了

Traceback (most recent call last): File "", line 1, in File "C:\Python27\lib\encodings\utf_16.py", line 16, in decode return codecs.utf_16_decode(input, errors, True) UnicodeDecodeError: 'utf16' codec can't decode bytes in position 32-33: illegal encoding

如果我遗漏了什么或者我的方法是错误的,请告诉我

编辑:有人问过截图 enter image description here


Tags: 文件textin文本readlineopencontent
3条回答

您可以指定与encoding参数一起使用的编码:

with open('text.ucs', 'r', encoding='utf-16') as f:
    text = f.read()

字符串被编码为UTF16-BE(Big-Endian),其工作原理是:

content.decode("utf-16-be")

哦,据我所知,您使用的是python2.x.x,但编码参数仅在python3.x.x中添加,我并不精通python2.x.x,但您可以在google上搜索io.打开例如尝试:

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

但是你需要输入io模块吗

相关问题 更多 >