【自动化办公】python批量替换word中的内容
background
例行吐槽:由于各种原因,放弃了目标检测这条路,换条路走走。
入职普普通通行政文员,搞搞事情。
发现有很多文件其实只是里面的一些东西需要替换,(其实用word的查找替换也可以,不过,搞搞事情嘛)。
模板中使用占位符,然后替换成数据。
1.导入包读取文件
from docx import Document
from docx.shared import Pt #磅数
from docx.oxml.ns import qn #chinese
#读取文件
document=Document('/Users/apple/Desktop/xxx.docx')
2.定义替换函数(这里代码非原创,忘记哪里看到的了orz)
def change_text(old_text, new_text,document):
#遍历文档内所有段落
all_paragraphs = document.paragraphs
for paragraph in all_paragraphs:
for run in paragraph.runs:
if old_text in run.text:
run.text = run.text.replace(old_text, new_text)
#遍历文档内所有表格
all_tables = document.tables
for table in all_tables:
for row in table.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
for run in paragraph.runs:
if old_text in run.text:
run.text = run.text.replace(old_text, new_text)
3. Input输入new_text与old_text构成字典
#输入公司名以及报价
G_list=[]
company_bonus=dict()
for i in range(1,4):
G_name=input("公司名字:")
G_bj=input("公司报价:")
G_list.append(G_name)
G_list.append(G_bj)
company_bonus['G%d'%(i)] = G_name
company_bonus['B%d'%(i)] = G_bj
4. 替换
for k,v in company_bonus:
old_text = f'{k}'
new_text = f'{v}'
replaceStr(old_text, new_text)
#保存文本
doc.save('/Users/apple/Desktop/xxxx.docx')