Python docx - 一行多色

Python docx - Multiple color in one line

我目前正在使用 python docx 库生成一个 word 文件。

我创建了多个 table 连接文本和变量。 当行中有变量时,我将它们标记为:var

我需要将分隔符 <>var 的颜色更改为红色以突出显示它。

我认为关于文本颜色的唯一方法是:

p=document.add_paragraph()
wp = p.add_run('I want this sentence colored red with fontsize=22')
wp.font.color.rgb = RGBColor(255,0,0)

但它是针对所有段落,而不是特定部分。

字符级格式(“字体”特征)在 运行 级别控制。 运行 是共享相同字符级格式的字符序列。因此,如果要在正常格式的段落中使用红色字符“运行”,则需要三个 运行;一个之前,一个红色,一个之后。

paragraph = document.add_paragraph()
paragraph.add_run("The part before the red bit ")
run = paragraph.add_run("the red bit")
run.font ... # --- make the font of this run red ---
paragraph.add_run(" the part after the red bit.")