1. 문자열을 스페이스로 분리하여 대체
s = 'Macron made the announcement to mark the opening of the Paris AI Summit.' # 바꾸고자 하는 단어들 li = ["announcement", "opening", "Summit."] # 새로운 단어 k = "Trump" # 스페이스로 분리해 단어 리스트를 만들고 바꿀 단어들과 같다면 새로운 단어로 대헤 res = ' '.join([k if word in li else word for word in s.split()]) print(res) -> Macron made the Trump to mark the Trump of the Paris AI Trump |
2. 정규표현 '|' 을 이용
import re s = 'Macron made the announcement to mark the opening of the Paris AI Summit.' # 바꾸고자 하는 단어들 li = ["announcement", "opening", "Summit."] # 새로운 단어 k = "Trump" # 정규표현 -> https://eldercoder.tistory.com/167 # 'aaa|bbb|ccc' : aaa 나 bbb 나 ccc 이 와도 OK res = re.sub("|".join(li), k, s) print(res) -> Macron made the Trump to mark the Trump of the Paris AI Trump |
3. for ... in replace 를 이용
s = 'Macron made the announcement to mark the opening of the Paris AI Summit.' # 바꾸고자 하는 단어들 li = ["announcement", "opening", "Summit."] # 새로운 단어 k = "Trump" for word in li: s = s.replace(word, k) print(s) -> Macron made the Trump to mark the Trump of the Paris AI Trump |
4. reduce 를 이용
from functools import reduce s = 'Macron made the announcement to mark the opening of the Paris AI Summit.' # 바꾸고자 하는 단어들 li = ["announcement", "opening", "Summit."] # 새로운 단어 k = "Trump" # reduct -> https://eldercoder.tistory.com/156 # 맨 마지막의 s 의 초기값 res = reduce( (lambda s, w: s.replace(w, k)), li, s) print(res) -> Macron made the Trump to mark the Trump of the Paris AI Trump |
'data science > python' 카테고리의 다른 글
dict 을 이용한 일괄 문자열 바꿔치기 (0) | 2025.02.12 |
---|---|
반복되는 특정 단어를 복수 단어로 바꿔치기 (0) | 2025.02.11 |
정규표현(regular expressions) (0) | 2025.02.07 |
*args and **kwargs (불특정 수의 함수인수) (0) | 2025.02.02 |
(Colab) Youtube 영상을 mp3 화일로 다운로드 (0) | 2025.02.01 |