Python- 'ascii'코덱이 바이트를 디코딩 할 수 없습니다
정말 혼란 스러워요. 나는 인코딩을 시도했지만 오류가 말했다 can't decode...
.
>>> "你好".encode("utf8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
문자열에 "u"접두사가있는 오류를 피하는 방법을 알고 있습니다. 인코딩이 호출되었을 때 왜 오류가 "디코딩 할 수 없는지"궁금합니다. 파이썬은 무엇을하고 있습니까?
"你好".encode('utf-8')
encode
유니 코드 객체를 객체로 변환 string
합니다. 그러나 여기에 string
객체가 없습니다 (u가 없기 때문에). 따라서 파이썬은 먼저 객체를 객체 로 변환해야 string
합니다 unicode
. 그래서 그것은
"你好".decode().encode('utf-8')
그러나 문자열이 유효한 ASCII가 아니기 때문에 디코딩이 실패합니다. 그래서 해독 할 수 없다는 불만이 생깁니다.
항상 유니 코드에서 바이트로 인코딩하십시오 .
이 방향 에서 인코딩을 선택하십시오 .
>>> u"你好".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print _
你好
다른 방법은 바이트에서 유니 코드로 디코딩하는 것입니다.
이 방향 에서 인코딩이 무엇인지 알아야합니다 .
>>> bytes = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print bytes
你好
>>> bytes.decode('utf-8')
u'\u4f60\u597d'
>>> print _
你好
이 점은 충분히 강조 할 수 없습니다. 유니 코드 "whack-a-mole"재생을 피하려면 데이터 수준에서 발생하는 상황을 이해하는 것이 중요합니다. 여기 다른 방법으로 설명되어 있습니다.
- 유니 코드 객체는 이미 디코딩되어 있으므로 호출하지 않습니다
decode
. - 바이트 문자열 객체는 이미 인코딩되어 있으므로 호출하지 않습니다
encode
.
이제 .encode
바이트 문자열 을 볼 때 Python 2는 먼저 암시 적으로 텍스트 ( unicode
객체) 로 변환하려고 시도합니다 . 마찬가지로 .decode
유니 코드 문자열 을 볼 때 Python 2는 암시 적으로 바이트 ( str
객체) 로 변환하려고 시도합니다 .
이러한 암시 적 변환은 호출했을 때 얻을 수있는 이유 입니다. 인코딩은 일반적으로 유형의 매개 변수를 허용하기 때문입니다 . 매개 변수를 수신하면 다른 인코딩으로 다시 인코딩하기 전에 유형의 객체에 대한 암시 적 디코딩이 있습니다. 이 변환은 기본 'ascii'디코더 †를 선택 하여 인코더 내부의 디코딩 오류를 제공합니다.Unicode
Decode
Error
encode
unicode
str
unicode
사실, 파이썬 3 방법에 str.decode
및 bytes.encode
도 존재하지 않는다. 그들의 제거는이 일반적인 혼란을 피하기위한 논쟁의 여지가있는 시도였다.
† ... 또는 모든 코딩 sys.getdefaultencoding()
언급; 보통 이것은 '아스키'입니다
당신은 이것을 시도 할 수 있습니다
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
또는
당신은 또한 다음을 시도 할 수 있습니다
.py 파일 맨 위에 다음 줄을 추가하십시오.
# -*- coding: utf-8 -*-
Python <3을 사용하는 경우 인터프리터에게 문자열 리터럴이 유니 코드u
임을 접두사로 앞에 붙여서 알려야합니다 .
Python 2.7.2 (default, Jan 14 2012, 23:14:09)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "你好".encode("utf8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> u"你好".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
추가 자료 : Unicode HOWTO .
u"你好".encode('utf8')
유니 코드 문자열을 인코딩하는 데 사용 합니다. 그러나을 나타내려면 "你好"
디코딩해야합니다. 처럼:
"你好".decode("utf8")
원하는 것을 얻을 수 있습니다. 인코딩 및 디코딩에 대해 더 많이 배울 수 있습니다.
In case you're dealing with Unicode, sometimes instead of encode('utf-8')
, you can also try to ignore the special characters, e.g.
"你好".encode('ascii','ignore')
or as something.decode('unicode_escape').encode('ascii','ignore')
as suggested here.
Not particularly useful in this example, but can work better in other scenarios when it's not possible to convert some special characters.
Alternatively you can consider replacing particular character using replace()
.
If you are starting the python interpreter from a shell on Linux or similar systems (BSD, not sure about Mac), you should also check the default encoding for the shell.
Call locale charmap
from the shell (not the python interpreter) and you should see
[user@host dir] $ locale charmap
UTF-8
[user@host dir] $
If this is not the case, and you see something else, e.g.
[user@host dir] $ locale charmap
ANSI_X3.4-1968
[user@host dir] $
Python will (at least in some cases such as in mine) inherit the shell's encoding and will not be able to print (some? all?) unicode characters. Python's own default encoding that you see and control via sys.getdefaultencoding()
and sys.setdefaultencoding()
is in this case ignored.
If you find that you have this problem, you can fix that by
[user@host dir] $ export LC_CTYPE="en_EN.UTF-8"
[user@host dir] $ locale charmap
UTF-8
[user@host dir] $
(Or alternatively choose whichever keymap you want instead of en_EN.) You can also edit /etc/locale.conf
(or whichever file governs the locale definition in your system) to correct this.
참고URL : https://stackoverflow.com/questions/9644099/python-ascii-codec-cant-decode-byte
'development' 카테고리의 다른 글
Maven Central에서 "치명적 경보 수신 : protocol_version"또는 "피어 인증되지 않음"이 표시되는 이유는 무엇입니까? (0) | 2020.07.27 |
---|---|
html5에서 투명 캔버스를 만들려면 어떻게해야합니까? (0) | 2020.07.27 |
클래스 이름 및 메소드 이름 드롭 다운 목록이 누락되었습니다 (시각적 스튜디오 설정). (0) | 2020.07.27 |
MySQL의 부울 값에 대한 부울 대 tinyint (1) (0) | 2020.07.27 |
로직 프로그래밍과 관련하여 Prolog와 miniKanren의 주요 기술적 차이점은 무엇입니까? (0) | 2020.07.27 |