data science/python
여러 단어를 한 단어로 바꿔치기
꼰대코더
2025. 2. 11. 15:10
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 |