ssung_인턴일지

4일차_Data preprocessing

ssungcohol 2024. 7. 7. 22:54

데이터 전처리

문제 상황

  • 공공 API를 통해 받은 데이터 파일이 하나의 인코딩 형식이 아닌 여러 개의 형식으로 작성

해결 방안

  • chardet 라이브러리를 사용하여 해결
import chardet

# 파일 인코딩 형식 확인
def detect_encoding(file_path):
	with open(file_path, 'rb') as f:
    	raw_data = f.read()
    result = chardet.detect(raw_data)
    return result['encoding']

 

코드 설명

  • 파일의 문자 인코딩 형식을 감지하기 위해 사용하는 라이브러리
import chardet
  • open을 사용하여 파일을 바이너리 모드('b')로 열기
  • f.read()를 호출하여 모든 내용을 읽고, 'raw_data' 변수에 저장
with open(file_path, 'rb') as f:
	raw_data = f.read()
  • chardet.detect를 호출하여 'raw_data' 의 인코딩 형식 감지
  • 감지한 인코딩 정보를 result 변수에 저장
  • result 딕셔너리에 'encoding' 키의 값을 반환 -> 키 값 = 인코딩 형식
result = chardet.detect(raw_data)
return result['encoding']
728x90

'ssung_인턴일지' 카테고리의 다른 글

8일차_Data Preprocessing(3)  (0) 2024.07.11
7일차_Data Preprocessing(2)  (0) 2024.07.08
5, 6일차_Data Preprocessing  (0) 2024.07.07
3일차_YOLOv7, v8  (0) 2024.07.07
2일차_Image Labeling  (0) 2024.07.02