用不同的字体写一个word文档

问题描述

我有3种字体。我想修改word文档,以便为每个字符(字母)随机分配或以我不介意的某种顺序分配三种字体之一。不能使两个连续字符具有相同的字体。

我尝试编写python脚本,但是我尝试了解docx-Python库的大部分内容,我认为只有段落级样式才可以。

这是我尝试过的,不确定是否有用。

import docx
from docx.shared import Pt

doc = docx.Document("hey.docx")

mydoc = docx.Document()

style1 = mydoc.styles['normal']
font1=style1.font
font1.name = 'Times New Roman'
font1.size = Pt(12.5)

style2 = mydoc.styles['normal']
font2=style2.font
font2.name = 'Arial'
font2.size = Pt(15)

all_paras = doc.paragraphs
for para in all_paras:
    mydoc.add_paragraph(para.text,style=style1)
    print("-------")
mydoc.save("bye.docx")

如果hey.docx的文本中带有“ Hello”:Bye.docx应该具有“ H(在A字体中)e(在B字体中)l(在C字体中)l(在A字体中)o(在B字体中) “

解决方法

在段落中将每个字符添加为单独的运行,并为每个运行分配 character 样式。

from docx import Document
from docx.enum.style import WD_STYLE_TYPE as ST

document = Document()

styles = document.styles
style_A = styles.add_style("A",ST.CHARACTER)
style_A.font.name = "Arial"
style_A.font.size = Pt(15)
style_B = styles.add_style("B",ST.CHARACTER)
style_B.font.name = "Times New Roman"
style_B.font.size = Pt(12.5)

paragraph = document.add_paragraph()
for idx,char in enumerate("abcde"):
    paragraph.add_run(char,style_A if idx % 2 else style_B)

document.save("output.docx")

我将留给您创建其他字符样式,并发明一种更复杂的方法来确定要分配给每个字符的样式。