使用Python-docx编写word文档时,如何更改段落中特定文本的字体?

How to change the font of particular text in a paragraph when writing a word document using Python-docx?

我正在使用 Python 解析 excel 电子表格并将文档写入 word 文档。我想突出显示二进制子字符串,例如'001' 使数字显示为深红色。我可以使用 re 找到子字符串,它是单引号之间的二进制数字序列的任何文本,这不是我的问题。问题是如何突出显示段落中的那些字符?我想要结束的格式如下所示:

如有任何帮助,我们将不胜感激。

from docx import Document 
from docx.shared import RGBColor 

document = Document() 
run = document.add_paragraph()
binary_run = run.add_run('your_binary_code')
binary_run.font.color.rgb =  RGBColor(rgb_color_code_goes_here)
cmplt_run = binary_run.add_run('rest of the text goes here')

这会将二进制代码的字体颜色更改为您提供的颜色代码。请参阅 python-docx documemtation 以了解更多信息。

感谢@Paandittya 的启发,这是我的工作代码:

def highlight_binary(par, text):
''' Add text to paragraph while highlighting binary in dark red
    intputs:
    par    => the paragraph to add text to
    text   => the text with 0 or more binary strings in it 
'''
BINARY_STR = re.compile("'[01]+'")

for occurance in re.findall(BINARY_STR, text):
    pos = text.find(occurance)
    par.add_run(text[:pos+1]) # +1 -> opening quote in normal text 
    text = text[pos+len(occurance)-1:] # -1 -> closing quote in normal text
    hl = par.add_run(occurance[1:-1]) # remove quotes from highlighted part
    hl.font.color.rgb = RGBColor(192,0,0)

if text: # any text left?
    par.add_run(text)