s = "hello world, have a great day"
r_dict = {"hello": "hi", "world": "earth", "great": "wonderful"}
1. Loop 를 이용한 replace
for key, value in r_dict.items(): s = s.replace(key, value) print(s) -> "hi earth, have a wonderful day" |
2. 정규표현 re.sub()
import re # "스페이스 + ( hello|world|great ) + 스페이스" # lambda match는 매치 될때마다 매치 문자열 오브젝트가 할당 => 문자열은 object.group() # s 는 초기 문자열 result = re.sub(r'\b(?:' + '|'.join(r_dict.keys()) + r')\b', lambda match: r_dict[match.group()], s) print(result) -> "hi earth, have a wonderful day" |
'data science > python' 카테고리의 다른 글
Dijkstra Algorithm (Google map 에서도 사용하는 경로 찾기) (0) | 2025.02.21 |
---|---|
(colab) web scrapping (0) | 2025.02.16 |
여러 단어를 한 단어로 바꿔치기 (1) | 2025.02.11 |
반복되는 특정 단어를 복수 단어로 바꿔치기 (0) | 2025.02.11 |
정규표현(regular expressions) (0) | 2025.02.07 |