UnicodeDecodeError: 'ascii' codec can't decode

拜拜、爱过 提交于 2019-12-14 00:31:59

问题


I'm reading a file that contains Romanian words in Python with file.readline(). I've got problem with many characters because of encoding.

Example :

>>> a = "aberație"  #type 'str'
>>> a -> 'abera\xc8\x9bie'
>>> print sys.stdin.encoding
UTF-8

I've tried encode() with utf-8, cp500 etc, but it doesn't work.

I can't find which is the right Character encoding I have to use ?

thanks in advance.

Edit: The aim is to store the word from file in a dictionnary, and when printing it, to obtain aberație and not 'abera\xc8\x9bie'


回答1:


What are you trying to do?

This is a set of bytes:

BYTES = 'abera\xc8\x9bie'

It's a set of bytes which represents a utf-8 encoding of the string "aberație". You decode the bytes to get your unicode string:

>>> BYTES 
'abera\xc8\x9bie'
>>> print BYTES 
aberație
>>> abberation = BYTES.decode('utf-8')
>>> abberation 
u'abera\u021bie'
>>> print abberation 
aberație

If you want to store the unicode string to a file, then you have to encode it to a particular byte format of your choosing:

>>> abberation.encode('utf-8')
'abera\xc8\x9bie'
>>> abberation.encode('utf-16')
'\xff\xfea\x00b\x00e\x00r\x00a\x00\x1b\x02i\x00e\x00'


来源:https://stackoverflow.com/questions/6541256/unicodedecodeerror-ascii-codec-cant-decode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!