import os
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
def replace_text_in_docx(file_path, old_text, new_text):
doc = Document(file_path)
font_name = "標楷體"
font_size = Pt(14)
for para in doc.paragraphs:
if old_text in para.text:
para.text = para.text.replace(old_text, new_text)
for run in para.runs:
run.font.name = font_name
run.font.size = font_size
run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
if old_text in cell.text:
cell.text = cell.text.replace(old_text, new_text)
for para in cell.paragraphs:
for run in para.runs:
run.font.name = font_name
run.font.size = font_size
run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
doc.save(file_path)
folder_path = r'G:\test' # 修改為你的資料夾路徑
replacements = [
('科室主管', '部門主管'),
('機關首長', '單位(副)主管')
]
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.lower().endswith('.docx'):
file_path = os.path.join(root, file)
for old_text, new_text in replacements:
replace_text_in_docx(file_path, old_text, new_text)
print(f"Modified {file_path}")
print("Replacement completed.")
python-docx
模組來讀取和修改.docx檔案的內容,可以使用pip install python-docx
來安裝
沒有留言:
張貼留言