Python pptx - 单元格中不同颜色的部分文本

Python pptx - part of text in cell with different color

我正在使用 pptx 模块生成带 table 的幻灯片。我可以更改每个单元格中的字体,但我还需要更改文本中特定单词的字体。例如 "Generating random sentence as example"。在这个世界上 "random" 是粗体。

text color in python-pptx module 发现了类似的情况,但那个适用于 "text frame" 而不是 cell。

欢迎任何advices/suggestions!

谢谢

如果您在该示例使用 text_frame 的地方使用 cell(或者在该特定示例中可能使用 tf),其余代码是相同的。所以要创建 "A sentence with a red word" 其中 "red" 显示为红色:

from docx.shared import RGBColor

# ---reuse existing default single paragraph in cell---
paragraph = cell.paragraphs[0]

# ---add distinct runs of text one after the other to
# --- form paragraph contents
paragraph.add_run("A sentence with a ")

# ---colorize the run with "red" in it---
red_run = paragraph.add_run("red")
red_run.font.color.rgb = RGBColor(255, 0, 0)

paragraph.add_run(" word.")

您可以在此处的文档中找到更多详细信息:
https://python-docx.readthedocs.io/en/latest/user/text.html#font-color