我得到了一个包含日元符号 (¥) 的字节数据。这似乎表示为 \xc2\xa5。
但是,我无法解码日元符号。例如,
yen = b"\xc2\xa5"
type(yen) # return bytes
yen.decode("utf-8") # return UnicodeEncodeError: 'ascii' codec can't encode character '\xa5' error
import chardet
chardet.detect(yen) # return {'confidence': 0.73, 'encoding': 'windows-1252'}
yen.decode("windows-1252") # return another UnicodeEncodeError: 'ascii' codec can't encode characters error
我的字节数据在其他方面可以解码为utf-8。无论您使用什么编码,都无法解码日元符号。
那么我该如何解码呢?
请您参考如下方法:
问题出在终端和 shell 中的设置。具体来说,为了使解码按预期工作,您的 sys.stdout.encoding 应该返回 UTF-8。
如果您没有得到 UTF-8,那么您应该检查 $LANG 变量。在我的例子中,它返回了 en_US.UTF-8,但是由于我的 ~/.zprofile 没有 export 关键字,sys .stdout.encoding 返回 US-ASCII,而不是 UTF-8。所以你应该在你的~/.zprofile(或~/.bash_profile)中设置为:
export LC_ALL="en_US.UTF-8"
export LANG="en_US.UTF-8"
现在你应该从 sys.stdout.encoding 得到 UTF-8。
有关在 macOS 上的 shell 和终端中设置正确语言环境的更多信息,请查看 the following question .
