如何在Python中解码日元符号?

时间:2016-12-07 06:19:46

标签: python encoding

我得到了包含日元符号(¥)的字节数据。这似乎表示为\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。无论您使用何种编码,都只能解码日元符号。

那我怎么解码呢?

1 个答案:

答案 0 :(得分:2)

问题来自终端和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"

现在你应该从UTF-8获得sys.stdout.encoding

有关在shell中设置正确的区域设置和在macOS上设置终端的更多信息,请查看the following question