다음은 인코딩을 추측 할 수있는 작은 스 니펫입니다. 그것은 latin1과 utf8 사이를 꽤 좋은 것으로 추측합니다. 바이트 문자열을 유니 코드 문자열로 변환합니다.
# Attention: Order of encoding_guess_list is import. Example: "latin1" always succeeds.
encoding_guess_list=['utf8', 'latin1']
def try_unicode(string, errors='strict'):
if isinstance(string, unicode):
return string
assert isinstance(string, str), repr(string)
for enc in encoding_guess_list:
try:
return string.decode(enc, errors)
except UnicodeError, exc:
continue
raise UnicodeError('Failed to convert %r' % string)
def test_try_unicode():
for start, should in [
('\xfc', u'ü'),
('\xc3\xbc', u'ü'),
('\xbb', u'\xbb'), # postgres/psycopg2 latin1: RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
]:
result=try_unicode(start, errors='strict')
if not result==should:
raise Exception(u'Error: start=%r should=%r result=%r' % (
start, should, result))
좋은 아이디어. 감사. –
나는 try-except에서 .decode()를 사용하여 (1) 성공한 변환을 깨거나 (2) encoding_guess_list를 다 써 버린 후 이것을 단순화하고 채택했다. 끝이 실패한 경우 'strict'대신 'replace'로 설정된 오류가있는 다른 .decode()를 적용합니다. – JDM