字节类型的UnicodeDecodeError

Sha*_*Ali 4 python decode utf-8 utf-16 python-3.x

使用Python 3.4我尝试使用utf-32解码字节类型时出现以下错误

Traceback (most recent call last):
  File "c:.\SharqBot.py", line 1130, in <module>
    fullR=s.recv(1024).decode('utf-32').split('\r\n')
UnicodeDecodeError: 'utf-32-le' codec can't decode bytes in position 0-3: codepoint not in range(0x110000)
Run Code Online (Sandbox Code Playgroud)

以及尝试将其解码为utf-16时的以下内容

  File "c:.\SharqBot.py", line 1128, in <module>
    fullR=s.recv(1024).decode('utf-16').split('\r\n')
UnicodeDecodeError: 'utf-16-le' codec can't decode byte 0x0a in position 374: truncated data
Run Code Online (Sandbox Code Playgroud)

当我使用utf-8解码时没有错误.s是连接到端口80上的抽搐IRC服务器irc.chat.twitch.tv的套接字.

它收到以下内容:

b':tmi.twitch.tv 001 absolutelyabot :Welcome, GLHF!\r\n:tmi.twitch.tv 002 absolutelyabot :Your host is tmi.twitch.tv\r\n:tmi.twitch.tv 003 absolutelyabot :This server is rather new\r\n:tmi.twitch.tv 004 absolutelyabot :-\r\n:tmi.twitch.tv 375 absolutelyabot :-\r\n:tmi.twitch.tv 372 absolutelyabot :You are in a maze of twisty passages, all alike.\r\n:tmi.twitch.tv 376 absolutelyabot :>\r\n'
Run Code Online (Sandbox Code Playgroud)

尝试解码到16和32时,我做错了吗?我想使用utf-32的原因是因为偶尔会有人发送一个不在utf-8中的字符而我希望能够接收它而不是因为utf-8不支持该字符而抛出错误.谢谢你的帮助.

小智 9

尝试使用encoding ='ISO-8859-1'

  • @CodeWarrior:假定原始文本是“ latin-1”(ISO-8859-1的友好名称)编码的,而不是“ utf-8”。或不是,但是“ latin-1”是一对一编码,其中每个字节都映射到一个字符,因此它只是掩盖错误并产生乱码。无论哪种方式。 (2认同)

Sha*_*ger 3

每个Unicode 序数都可以用 UTF-8 表示,如果decodeUTF-8 不起作用,那是因为正在传输的字节采用不同的编码,或者数据是混合文本和二进制数据,并且只有其中一些是UTF-8。文本很可能UTF-8 编码的(大多数网络协议都是),因此非 UTF-8 数据将是帧数据等,并且需要进行解析以提取文本数据。

任何在文本/二进制情况下掩盖此类错误的尝试都只会消除问题,而不是解决问题。您需要知道数据的编码(以及格式,如果不是所有具有单一编码的文本数据),并使用它。您收到的数据不会像您希望的那样神奇地变成 UTF-16 或 UTF-32。