프로그래밍/Python

정규표현식_python 단어만 남기고 비단어 문자 제거

O'bin 2024. 4. 25. 16:16

🔷 예제 코드

 

1
2
3
4
5
6
7
8
9
import re
 
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
 
words = [word for word in re.sub(r'\W+'' ', paragraph).lower().split() if word not in banned]
 
print(words)    
# ['bob', 'a', 'ball', 'the', 'ball', 'flew', 'far', 'after', 'it', 'was']
cs

 

 

🔷 re.sub(r'\W+', ' ', paragraph)

=> paragraph라는 문자열에서 연속된 모든 비단어 문자를 찾아 이를 단일 공백 문자 ' '로 대체

 

 

🔷 \W 와 \w의 차이

  • \W
    • \W = non-word character = 공백, 구두점, 기타 특수 문자 등
    • "Hello, world!"에서 \W는 쉼표(,), 공백( ),느낌표(!)
  •  \w
    • \w =word character
    • 알파벳(a-z, A-Z), 숫자(0-9), 밑줄(_)