본문 바로가기

이거슨 상식!

[aihub 데이터처리] 특수문자 제거 (한줄 명령어, code포함)

aihub 데이터에 왠... 한글이 많이 들어있다....

짜증난다.. 

 

하위파일에 특수문자가 들어있을경우 그냥 rename 때렸고, 

image 와 라벨 페어 맞추기 위해, 

json 파일내 파일명에서는 아래처럼 바꿔줬다. 

아오 짜증나. 

 

- 파일명 제거는 파이썬 참고.

-파일내 특수문자 제거는 sed로 함. 

 sed -e 's/치환대상/치/g'             

 

 

## 하위 파일들을 찾고,  하위 파일 "내용"에 특수문자 포함되어 있을 경우 제거 

##  실행 후 결과 출력 sed -e 

find . -type f -name "*.json" -print0 | xargs -0 sed -e 's/\\uace0//g'

 

## 파일에 진짜 쓰기 sed -i 

find . -type f -name "*.json" -print0 | xargs -0 sed -i 's/\\uace0//g'

 

파일명에 특수문자("░φ")  함되어있을 경우 정규식을 통한 제거

 

r"[^0-9a-zA-Z_.-]" 

위 구문이 숫자, a-z, A-Z, _ , . , - 를 제외한 나머지는 모두 sub하라는 의미이다. 

 

한글 범위는 아래와 같다. 아래 범위를 넣어주면 <가-힣> 을 뺄 수 있다고 한다. 

   \uAC00-\uD7A3   

 

 

import os
import sys
import re

# set the search directory path
search_path='./1_6/image/VS5_sa-st/'

if len(sys.argv) >1 :
    search_path=sys.argv[1]

# loop through all files in the directory and its subdirectories
for root, dirs, files in os.walk(search_path):
    for filename in files:
        # check if the filename contains the "░φ" string
        new_filename = re.sub(r"[^0-9a-zA-Z_.-]", "", filename)
        #new_filename = re.sub(r"[\uAC00-\uD7A3_-]", "", filename)

        #if "░φ" in filename:
        print(new_filename)
        # construct the new filename by replacing the "░φ" string with an empty string
        #new_filename = filename.replace("░φ", "")
        # construct the full file paths for the old and new filenames
        old_file_path = os.path.join(root, filename)
        new_file_path = os.path.join(root, new_filename)
        # rename the file using os.rename()
        os.rename(old_file_path, new_file_path)
~

 

 

상세 설명 1 (sed. 11번 항목 참고)

https://today-carpediem.tistory.com/31

상세 설명 2 (정규식)

https://codechacha.com/ko/python-remove-special-letters/