반응형

파이썬, 한글 인코딩 형식 검사

글. 수알치 오상문

 

먼저 chardet 모듈을 설치합니다.


> pip install chardet

 

다음은 예제 코드입니다.

 

# 한글 인코딩 형식 검사
# encoding_checker.py
# by 오상문
#
# pip install chardet

import chardet

text = "안녕하세요"  # 파이썬3은 기본으로 utf-8 인코딩 사용 

result = chardet.detect(text.encode())
encoding = result['encoding']
print(encoding)  # utf-8

cp949_byte_code = text.encode('euc-kr')  # 'cp949'와 같음
print(cp949_byte_code)  # b'\xbe\xc8\xb3\xe7\xc7\xcf\xbc\xbc\xbf\xe4'

result = chardet.detect(cp949_byte_code)
encoding = result['encoding']
print(encoding)  # EUC-KR

decoded_text = cp949_byte_code.decode('cp949')  # 원래 utf-8로 변경
print(decoded_text)  # 안녕하세요


[실행 결과]
utf-8
b'\xbe\xc8\xb3\xe7\xc7\xcf\xbc\xbc\xbf\xe4'
EUC-KR
안녕하세요

반응형

+ Recent posts