파이썬을 기본적으로 인코딩 할 수없는 숯으로 교체하십시오.

StackOverflow https://stackoverflow.com/questions/1933184

  •  20-09-2019
  •  | 
  •  

문제

파이썬을 인코딩 할 수없는 숯을 무시하게 만들고 싶습니다. 단순히 문자열로 교체함으로써 "<could not encode>".

예 : 기본 인코딩이 ASCII라고 가정하면 명령

'%s is the word'%'ébác'

양보 할 것입니다

'<could not encode>b<could not encode>c is the word'

내 모든 프로젝트에서 이것을 기본 동작으로 만들 수있는 방법이 있습니까?

도움이 되었습니까?

해결책

그만큼 str.encode 함수는 오류 처리를 정의하는 선택적 인수를 가져옵니다.

str.encode([encoding[, errors]])

문서에서 :

인코딩 된 문자열 버전을 반환합니다. 기본 인코딩은 현재 기본 문자열 인코딩입니다. 다른 오류 처리 체계를 설정하기 위해 오류가 주어질 수 있습니다. 오류의 기본값은 '엄격한'이므로 인코딩 오류가 유니 코드 에러가 발생 함을 의미합니다. 다른 가능한 값은 '무시', '대체', 'xmlcharrefreplace', 'backslashreplace'및 codecs.register_error ()를 통해 등록 된 기타 이름은 Codec 기본 클래스 섹션을 참조하십시오. 가능한 인코딩 목록은 섹션 표준 인코딩을 참조하십시오.

당신의 경우, codecs.register_error 기능이 관심을 가질 수 있습니다.

참고 사항 나쁜 숯]

그건 그렇고, 사용할 때 주목하십시오 register_error 주의를 기울이지 않는 한 개별 나쁜 캐릭터뿐만 아니라 연속 나쁜 캐릭터 그룹을 문자열로 대체 할 수 있습니다. 문자당이 아닌 나쁜 숯의 실행 당 오류 핸들러에 한 번의 호출을받습니다.

다른 팁

>>> help("".encode)
Help on built-in function encode:

encode(...)
S.encode([encoding[,errors]]) -> object

Encodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. **Other possible values are** 'ignore', **'replace'** and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that is able to handle UnicodeEncodeErrors.

예를 들어 :

>>> x
'\xc3\xa9b\xc3\xa1c is the word'
>>> x.decode("ascii")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
>>> x.decode("ascii", "replace")
u'\ufffd\ufffdb\ufffd\ufffdc is the word'

Codecs.register_error에 자신의 콜백을 추가하여 원하는 문자열로 교체하십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top