🔷 예제 코드
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), 밑줄(_)
'프로그래밍 > Python' 카테고리의 다른 글
백준_python 11659번 구간 합 구하기 4 (누적합, 시간초과) (0) | 2024.04.27 |
---|---|
백준_python 9375번 패션왕 신해빈(딕셔너리) (1) | 2024.04.26 |
백준_python 10942번 팰린드롬?(시간초과, DP) (0) | 2024.04.23 |
백준_python 1003번 피보나치 함수(다이나믹프로그래밍) (0) | 2024.04.22 |
백준_python 2178번 미로 탐색(그래프, BFS) (0) | 2024.04.21 |