Python으로 특수기호 제거하는 예제입니다.
자연어처리, 크롤한 데이터 정제 등을 할 때 특수문자를 제거하거나 클린징을 해야 할 때 많이 하는 작업입니다. 비정형 데이터 중에서 텍스트(문자열)을 다루다보면 평생을 따라다닐지도 모를 그런 작업입니다.
가장 빠른 것은 translate() 메서드를 사용하는 것이고
그 다음은 string.replace() 메서드를 사용하는 것이고
가장 느린 것은 정규표현식을 사용하는 것입니다.
속도가 문제되지 않으면 (느려도 되면) 정규표현식을 사용하는 것이 가장 유연하고 좋습니다. 특정 문자를 넣고 빼거나 숫자를 포함한다거나 하는 여러가지 작업을 할 수 있습니다.
3가지 방법의 소스코드를 참고하세요.
translate() 함수 사용하기
1 2 3 4 5 6 7 8 9 10 11 |
# strings 패키지의 translate() 함수를 사용하여 특수기호를 제거하는 예제 import string input_string = '!hi. wh?at is the weat[h]er lik?e. !@##$%%^^&*)_+{}|?"' output_string = input_string.translate(str.maketrans('', '', string.punctuation)) print(output_string) # Returns: hi what is the weather like # 제거되는 특수기호는 아래와 같다. print(string.punctuation) # Returns: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ |
정규표현식 regular expression 사용하기
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# 정규표현식을 사용하여 특수기호를 제거하는 예제 import re input_string = '!hi. wh?at is the weat[h]er lik?e. !@##$%%^^&*)_+{}|?"' output_string = re.sub(r'[^\w\s]', '', input_string) print(output_string) # Returns: hi what is the weather like # 좀더 빨리 하려면 정규표현식을 컴파일하는 것이 좋다. pattern_punctuation = re.compile(r'[^\w\s]') output_string = pattern_punctuation.sub('', input_string) print(output_string) |
string.replace() 사용하기
1 2 3 4 5 6 7 8 9 |
# string.replace() 함수를 사용하여 특수기호를 제거하는 예제 import string input_string = '!hi. wh?at is the weat[h]er lik?e. !@##$%%^^&*)_+{}|?"' for character in string.punctuation: input_string = input_string.replace(character, '') print(input_string) # Returns: hi what is the weather like |
소스 파일
github에 노트북으로도 올려놨습니다.
https://github.com/euriion/python-exams/blob/main/remove-punctuations.ipynb