Python으로 파일에서 특정 단어 찾기와 치환하기
텍스트 파일을 다루다 보면 특정 단어를 찾아서 바꾸거나, 몇 번 등장했는지 세거나, 위치까지 확인해야 할 때가 있습니다. 이 글에서는 Python의 re 모듈과 문자열 메서드를 활용해 그 방법을 정리합니다.
1. 특정 단어 치환하기
import re
replace_dict = {
"dog": "cat",
"hello": "hi"
}
with open("input.txt", "r", encoding="utf-8") as f:
content = f.read()
for old, new in replace_dict.items():
pattern = r"\b" + re.escape(old) + r"\b"
content = re.sub(pattern, new, content)
with open("output.txt", "w", encoding="utf-8") as f:
f.write(content)
\b는 단어 경계를 의미하므로 정확히 일치하는 단어만 치환됩니다.
2. 특정 단어 개수 세기
text = "hello world, hello python, hello AI"
word = "hello"
count = text.count(word) # 부분 문자열 기준
print(count) # 3
# 단어 단위로 정확히 세기
pattern = r"\b" + re.escape(word) + r"\b"
matches = re.findall(pattern, text)
print(len(matches)) # 3
3. 접두어가 포함된 단어 추출하기
text = "aaa.ccdh bbb.tttjj ccc.kkk aaa.zzz bbb.123"
prefixes = ["aaa.", "bbb."]
pattern = r"(?:aaa\.|bbb\.)\w+"
matches = re.findall(pattern, text)
print(matches)
# ['aaa.ccdh', 'bbb.tttjj', 'aaa.zzz', 'bbb.123']
4. 파일에서 찾기
with open("input.txt", "r", encoding="utf-8") as f:
content = f.read()
pattern = r"(?:aaa\.|bbb\.)\w+"
matches = re.findall(pattern, content)
if matches:
print("찾은 단어들:", matches)
else:
print("패턴에 맞는 단어가 없습니다.")
5. 위치까지 확인하기
for match in re.finditer(pattern, content):
print("찾은 단어:", match.group())
print("시작 위치:", match.start())
print("끝 위치:", match.end())
이렇게 하면 단어가 어디서 발견되었는지 인덱스까지 알 수 있습니다.
마무리
Python의 re 모듈을 활용하면 단순 치환부터 단어 개수 세기, 위치 추적까지 다양하게 처리할 수 있습니다. 텍스트 데이터 전처리나 로그 분석에 매우 유용하게 활용할 수 있으니 꼭 익혀두세요!
반응형
'파이썬 스크립트' 카테고리의 다른 글
| 네이버 맛집 정보 수집 + 소형 AI JSON 변환 기획서 (1) | 2026.07.21 |
|---|---|
| SQLite 튜토리얼: Oracle 개발자를 위한 핵심 차이점 정리 (0) | 2026.06.30 |
| 블로그 이전 완료... (1) | 2026.06.11 |
| Python에서 5100개 키워드 포함 여부 빠르게 검사하기 (1) | 2026.05.14 |
| 자동 글쓰기로 티스토리와 네이버 블로그을 동시에 키워 보겠습니다. (0) | 2026.03.25 |