Usage scenario: It is suitable for long documents. We do not need to input text one by one. It is more convenient to do typesetting in Word in advance, and it does not need to manually set the font, size and other typesetting through Python.
Case: Replace all "Peigong" in the article "Hongmen Feast" with "Liu Bang". Replace the famous sentence "Very urgent! Today, Xiang Zhuang is pulling the sword, which often means Liu Bangya." with "Xiang Zhuang is dancing the sword, which means Peigong."
The template document of Hongmen Banquet is roughly as follows:
Execution code:
'''Word格式套用之套用模板''' from docx import Document from docx.shared import Pt from docx.oxml.ns import qn document=Document('鸿门宴.docx') # 导入模板文件 document.styles['Normal'].font.name=u'微软雅黑' # 设置默认字体,和字号 document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'),u'微软雅黑') document.styles['Normal'].font.size=Pt(12) def change_text(old_text,new_text): # 定义一个函数,将久闻字换成新文字 all_paragraphs=document.paragraphs # 获取所有的段落 for paragraph in all_paragraphs: for run in paragraph.runs: # 获取段落中不同格式的句子 run_text=run.text.replace(old_text,new_text) # 将文字进行替换 run.text=run_text all_tables=document.tables # 获取所有表格,这里没有表格,暂时用不到 for table in all_tables: # 依次获取表格的内容 for rows in table.rows: for cell in rows.cells: cell_text=cell.text.replace(old_text,new_text) # 替换表格里的新旧内容 cell.text=cell_text change_text('沛公','刘邦') # 调用函数 change_text('甚急!今者项庄拔剑舞,其意常在刘邦也。','项庄舞剑,意在沛公') document.save('鸿门宴_替换.docx') # 保存文件 执行程序完成以后的效果图: