如何在 python docx 中更改句子的字体样式

How to change font styles in python docx for a sentence

我们如何将字体名称、大小等应用到 python docx 中的 add_run()。
我尝试了以下但它不起作用。

run = Document().add_paragraph().add_run()
font = run.font
font.name = “MS Gothic”
Document().add_paragraph().add_run(“Some random text”)

之前有人回答过,你可以看看,你必须应用一个样式。我已经测试了以下内容,它似乎有效。

import docx
document = docx.Document()
run = document.add_paragraph().add_run()
'''Apply style'''
style = document.styles['Normal']
font = style.font
font.name = 'MS Gothic'
font.size = docx.shared.Pt(15)
document.add_paragraph('Some text').add_run()

对于每个句子,请尝试以下操作:

import docx
document = docx.Document()
run = document.add_paragraph().add_run()
'''Apply style'''
style = document.styles['Normal']
font = style.font
font.name = 'MS Gothic'
font.size = docx.shared.Pt(15)
paragraph = document.add_paragraph('Some text\n')
'''Add another sentence to the paragraph'''
sentence = paragraph.add_run('A new line that should have a different font')
'''Then format the sentence'''
sentence.font.name = 'Arial'
sentence.font.size = docx.shared.Pt(10)