写一个word文档,每个字符有不同的字体
Write a word document with each character having a different font
我有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)"
在段落中将每个字符添加为单独的 运行,并为每个 运行.
分配一个 字符 样式
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")
我将留给您创建其他字符样式并发明一种更复杂的方法来确定为每个字符分配哪种样式。
我有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)"
在段落中将每个字符添加为单独的 运行,并为每个 运行.
分配一个 字符 样式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")
我将留给您创建其他字符样式并发明一种更复杂的方法来确定为每个字符分配哪种样式。