반응형

한글 문자열을 검사해서 utf-8 아니면 utf-8 인코딩으로 자동 변환

 

글. 수알치 오상문

 

먼저 다음 명령으로 chardet 모듈을 설치합니다.

 

pip install chardet

 

다음은 파이썬 코드입니다.

 

# 한글 문자열을 검사해서 utf-8 아니면 utf-8 인코딩 변환 예제
# convert_utf8.py
# by 오상문
#
# pip install chardet

import chardet

def convert_to_utf8(text):
    try:
        result = chardet.detect(text.encode())  # 문자열 인코딩 형식 검사
    except Exception as e:
        result = chardet.detect(text)  # 문자열 인코딩 형식 검사
    # print(result) 
    encoding = result['encoding']
    
    if encoding != 'utf-8':  # utf-8이 아닌 경우 디코딩하여 utf-8로 인코딩
        d_text = text.decode(encoding) # 디코딩하여 문자열로 변환
        text = d_text.encode('utf-8').decode()
        
    return text

# Test ------------
text1 = "안녕하세요"  # utf-8
text2 = "안녕하세요".encode('cp949')  # CP949, euc-kr
text3 = "안녕하세요".encode('utf-16') # utf-16

print(text1)
print(text2)
print(text3)

converted_text1 = convert_to_utf8(text1)
converted_text2 = convert_to_utf8(text2)
converted_text3 = convert_to_utf8(text3)

print(converted_text1)  # 안녕하세요.
print(converted_text2)  # 안녕하세요.
print(converted_text3)  # 안녕하세요.


[실행 결과]
안녕하세요
b'\xbe\xc8\xb3\xe7\xc7\xcf\xbc\xbc\xbf\xe4'
b'\xff\xfeH\xc5U\xb1X\xd58\xc1\x94\xc6'
안녕하세요
안녕하세요
안녕하세요

반응형

+ Recent posts