python操作word文件,替换文本保留原格式

这里的替换文本保留原格式是指,替换word中有规律的字符串,比如将6-7…6-28全部加一,替换成6-8…6-29

#coding: utf-8
import os, sys
# 安装docx: pip install python_docx
from docx import Document
from docx.shared import Inches

file_name = os.path.join(sys.path[0], "bylw.docx")
print(f'file name: {file_name}')

#创建 Document 对象,相当于打开一个 word 文档
doc = Document(file_name)

# 参考:https://www.zhihu.com/question/64235925
def replaceStr(old_text, new_text):
    for p in doc.paragraphs:
        if old_text in p.text:
            inline = p.runs
            for i in inline:
                if old_text in i.text:
                    text = i.text.replace(old_text, new_text)
                    i.text = text
                    
key_num = 28
while True:
    old_text = f'6-{key_num}'
    new_text = f'6-{key_num + 1}'
    replaceStr(old_text, new_text)
    key_num -= 1
    if key_num == 7:
        break

#保存文本
doc.save('demo3.docx')

你可能感兴趣的:(Python)