批量替换为(多个文件,在同一目录下,批量替换,几秒完成)
源码下载:
https://download.csdn.net/download/lm19770429/15483485
https://download.csdn.net/download/lm19770429/15483468
导入必要的包
import os
from docx import Document
from docx.shared import *
from docx.enum.text import *
from docx.shared import Pt, Cm, RGBColor
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
定义相关变量
os.chdir('C:\\pythonAPP\\教案') #在程序同级目录下建立一个名为“教案”的文件夹,把旧教案考入该文件夹
jieci='1-2节'
xueqi='(2020 —2021 学年度第二学期)'
src_class='2018级网络安全与执法班'
dst_class='2019级网络安全与执法班'
query_zhou='教学周3-4节'
src_course='计算机操作系统'
dst_course='计算机操作系统'
#for each in os.listdir( ): os.rename(each,"《计算机"+each) #批量文件改名
for each in os.listdir( ):
#each='《计算机操作系统》教案06.docx'
sn=each.split('.')[0][-2:]
doc=Document(each)
doc.paragraphs[1].clear()
doc.paragraphs[1].add_run(xueqi)
doc.paragraphs[1].runs[0].font.name='宋体'
doc.paragraphs[1].runs[0].font.size=Pt(12)
r=doc.paragraphs[1].runs[0]._element.rPr.rFonts
r.set(qn('w:eastAsia'),'宋体')
for c in doc.tables[0].rows[0].cells:
if src_course in c.text:
c.text=dst_course
for c in doc.tables[0].rows[1].cells:
if src_class in c.text:
c.text=dst_class
if query_zhou in c.text:
c.text='第{}教学周{}'.format(sn,jieci)
for run in c.paragraphs[0].runs:
run.font.name='宋体'
run.font.size=Pt(10.5)
r=run._element.rPr.rFonts
r.set(qn('w:eastAsia'),'宋体')
doc.save('新《'+dst_course+'》教案'+sn+each[-5:]) #新增修改文件名