[python] 파이썬으로 워드 문서에서 특정 텍스트 바꾸기

워드 문서에서 특정 텍스트를 바꾸는 일은 자동화를 위해 많이 사용되는 작업 중 하나입니다. 파이썬을 사용하면 워드 문서를 쉽게 열고 수정할 수 있습니다. 이번 글에서는 python-docx 라이브러리를 사용하여 워드 문서에서 특정 텍스트를 바꾸는 방법을 알아보겠습니다.

필요한 라이브러리 설치

먼저 python-docx 라이브러리를 설치해야 합니다. 아래의 명령어를 사용하여 설치하세요.

pip install python-docx

예제 코드

다음은 워드 문서에서 특정 텍스트를 바꾸는 예제 코드입니다. 워드 문서 파일(document.docx)에서 ‘apple’을 ‘orange’로 바꾸는 예제입니다.

from docx import Document

# 워드 문서 열기
doc = Document('document.docx')

# 모든 단락을 순회하며 텍스트 바꾸기
for paragraph in doc.paragraphs:
    if 'apple' in paragraph.text:
        paragraph.text = paragraph.text.replace('apple', 'orange')

# 모든 테이블을 순회하며 텍스트 바꾸기
for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
            if 'apple' in cell.text:
                paragraphs = cell.paragraphs
                for paragraph in paragraphs:
                    paragraph.text = paragraph.text.replace('apple', 'orange')

# 수정된 문서 저장
doc.save('modified_document.docx')

위의 예제 코드에서 document.docx는 수정할 워드 문서 파일 경로를, modified_document.docx는 수정이 완료된 파일의 저장 경로를 나타내고 있습니다. 코드에서 ‘apple’을 찾아서 ‘orange’로 바꾸고, 수정된 문서를 save() 메서드를 통해 저장합니다.

참고 자료