[英]How to change the font of particular text in a paragraph when writing a word document using Python-docx?
I am using Python to parse an excel spreadsheet and write documentation to a word document. 我正在使用Python解析excel电子表格并将文档写入Word文档。 I want to highlight binary substrings eg '001' by having the numbers appear in dark red. 我想通过数字以深红色突出显示二进制子字符串,例如'001'。 I can find the substrings using re being any text which is a binary number sequence between single quotes, that is not my question. 我可以使用re作为任何文本查找子字符串,这是单引号之间的二进制数字序列,这不是我的问题。 The question is how do I put the highlighting on just those characters within the paragraph? 问题是如何将高亮显示在段落中的那些字符上? The format I would like to end up with is like the following: 我想要的最终格式如下:
Any help would be appreciated. 任何帮助,将不胜感激。
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')
This will change the font color of ur binary code to the color code you provide. 这会将您的二进制代码的字体颜色更改为您提供的颜色代码。 Refer python-docx documemtation to understand more. 请参阅python-docx文档,以了解更多信息。
Thanks to @Paandittya for the inspiration, here is my working code: 感谢@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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.