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)) # 33. 접두어가 포함된 단어 추출하기
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 모듈을 활용하면 단순 치환부터 단어 개수 세기, 위치 추적까지 다양하게 처리할 수 있습니다. 텍스트 데이터 전처리나 로그 분석에 매우 유용하게 활용할 수 있으니 꼭 익혀두세요!
댓글 없음:
댓글 쓰기