字节类型的 UnicodeDecodeError

新手上路,请多包涵

使用 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)

以及尝试将其解码为 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

当我使用 utf-8 解码时没有错误。 s 是连接到端口 80 上的 twitch 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'

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

原文由 Shariq Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 670
1 个回答

尝试使用 encoding = ‘ISO-8859-1’

原文由 RATAN KUMAR 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题