티스토리 뷰

INTRO

macOS 파일이름 utf-8 encoding

macOS 파일이름 한글 자모분리 해결 : nomalize

 

1. chardet 설치 : 문자열 인식 라이브러리

$ pip install --upgrade pip
$ pip install chardet

 

2. utf-8 encoding & 한글 자소분리 normalize

filename_encoding_korean_normalize.py
# -*- coding: utf-8 -*-
import os
import chardet
from unicodedata import normalize
import shutil


fpath = "./test_files"
wpath = "./test_output"

flists = os.listdir(fpath)

print(flists)

for flist in flists:
	## check_encode
	check_encode = chardet.detect(flist.encode())
	print("flist:{} | check_encode:{}".format(flist,check_encode['encoding']))

	fname_in = os.path.join(fpath,flist)
	## convert to utf8
	if check_encode['encoding'] != "utf-8":
		if flist == ".DS_Store":
			pass
		else:
			with open(fname_in, "r", encoding = check_encode['encoding'], errors="surrogateescape") as fin:
				file_chunk = fin.read()			
			fname_out = os.path.join(wpath,flist)
			with open(fname_out, "w", encoding = "utf-8", errors="surrogateescape") as fout:
				fout.write(file_chunk)
	else:
		## korean normalize : NFC, NFD
		fname_norm = normalize("NFC", flist)
		# print(fname_norm)

		## 파일들 중 반복되는 제목 등 제거
		if "반복되는제목" in fname_norm:
			fname_norm = fname_norm.replace("반복되는제목","")
			# print(fname_norm)
		
        ## 최종 파일 복사
		fname_norm_out = os.path.join(wpath,fname_norm)
		shutil.copyfile(fname_in, fname_norm_out)

fout_lists = os.listdir(wpath)
print(fout_lists)

 

# 참고 : ascii 등 unicode bit 구성이 다른 경우 utf-8로 변경 안됨

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함