python-pptx库的个人优化
因为工作原因,最近一直在使用python-pptx这个库,库的功能比较完备,但是通过paragraphs和runs来定位某处需要修改的地方在实现起来比较花费时间,并且针对于一些需要不定时修改格式模板的ppt这种定位方式会带来极其大的工作量,后来我在使用python docxtemplate库时发现这种在ppt中插入变量然后用python来渲染变量赋值的方式很便捷,更利于ppt模板的维护,修改,所以写了这个函数,不用区分页码,而且可以保存变量书写时的文字格式,比如字体啊颜色什么的,遍历ppt中所有元素然后渲染保存。
例:
渲染:
渲染结果:
我要上代码啦:
from pptx import Presentation import pptx import re __author__='chs' def render(path_open,dic,path_save):##这个函数用来渲染全局文本框内文字并保留格式,参数path_open是需修改的ppt路径,dic是渲染字典,path_save是另存为地址 p=-1;s=-1;t=-1;r=-1 reelyment="chs(.+?)chs" comelyment=re.compile(reelyment) prs=Presentation(path_open) for page in prs.slides: p=p+1 s=-1 for shape in page.shapes: s=s+1 t=-1 if isinstance(shape,pptx.shapes.placeholder.SlidePlaceholder)==True or isinstance(shape,pptx.shapes.autoshape.Shape)==True: for parag in shape.text_frame.paragraphs: t=t+1 r=-1 for runchs in parag.runs: r=r+1 count=comelyment.findall(runchs.text) if len(count)!=0: try: prs.slides[p].shapes[s].text_frame.paragraphs[t].runs[r].text=prs.slides[p].shapes[s].text_frame.paragraphs[t].runs[r].text.replace(count[0],dic.get(count[0])).replace('chs','').replace(" ","") except TypeError: raise TypeError('%s变量未指定,看看变量名字是不是写错了,赋值是不是str类型,不是str写不到ppt里'%(count[0])) prs.save(path_save)