zhiqingstudy

Be a young person with knowledge and content

This period will learn a small case of python automatic generation of word files. Word format is applied to create templates.

Requirement: Most of the contents of a batch of word files are the same, but a noun needs to be replaced. For example, the first "Peigong" in each paragraph of the article "Hongmen Feast" is changed to "Liu Bang", "Liu Ji", "Han Gaozu" and "Han Taizu", and the file names are respectively saved as: Hongmen Feast - Liu Bang.docx, Hongmen Feast - Liu Ji.docx, Hongmen Feast - Han Gaozu. docx, Hongmen Feast - Han Taizu. docx.

Python automatically generates word files, and word format is applied to create templates

The codes are as follows:

# coding=gbk
from docx import Document # 导入docx模块
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT # 段落对其
from docx.shared import Pt # 字号
from docx.oxml.ns import qn # 字体


name_list=['刘邦','刘季','汉高祖','汉太祖'] # 设置名称列表
for name in name_list:

    def add_context(context):
        p=document.add_paragraph() # 添加段落
        p.alignment=WD_PARAGRAPH_ALIGNMENT.LEFT # 段落左对齐
        r=p.add_run(str(context)) # 段落里添加文字
        r.font.size=Pt(10) # 字体大小16磅
        p.space_after=Pt(50) # 段后5磅
        p.space_before=Pt(50) # 段前5磅


    # 设置默认字体
    document = Document()
    document.styles['Normal'].font.name = u'黑体'
    document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体')

    # 添加段落
    add_context('%s军霸上,未得与项羽相见。沛公左司马曹无伤使人言于项羽曰:“沛公欲王关中,使子婴为相,珍宝尽有之。”项羽大怒曰:“旦日飨士卒,为击破沛公军!”当是时,项羽兵四十万,在新丰鸿门;沛公兵十万,在霸上。范增说项羽曰:“沛公居山东时,贪于财货,好美姬。今入关,财物无所取,妇女无所幸,此其志不在小。吾令人望其气,皆为龙虎,成五采,此天子气也。急击勿失!”'% name)
    add_context('楚左尹项伯者,项羽季父也,素善留侯张良。张良是时从%s,项伯乃夜驰之沛公军,私见张良,具告以事,欲呼张良与俱去,曰:“毋从俱死也。”张良曰:“臣为韩王送沛公,沛公今事有急,亡去不义,不可不语。”良乃入,具告沛公。沛公大惊,曰:“为之奈何?”张良曰:“谁为大王为此计者?”曰:“鲰生说我曰:‘距关,毋内诸侯,秦地可尽王也。’故听之。”良曰:“料大王士卒足以当项王乎?”沛公默然,曰:“固不如也。且为之奈何?”张良曰:“请往谓项伯,言沛公不敢背项王也。”沛公曰:“君安与项伯有故?”张良曰:“秦时与臣游,项伯杀人,臣活之。今事有急,故幸来告良。”沛公曰:“孰与君少长?”良曰:“长于臣。”沛公曰:“君为我呼入,吾得兄事之。”张良出,要项伯。项伯即入见沛公。沛公奉卮酒为寿,约为婚姻,曰:“吾入关,秋毫不敢有
comment
head sculpture
Code:
Related

Why you shouldn't stay at a job for more than 2 years?

3 harsh facts long-distance relationships

how to keep your girlfriend interested in a long-distance relationship




Unless otherwise specified, all content on this website is original. If the reprinted content infringes on your rights, please contact the administrator to delete it
Contact Email:2380712278@qq.com

Filing number:皖ICP备19012824号