使用python更改word文档中单个单词的颜色

问题描述 投票:0回答:1

我想在将 Word 文档保存为新文档之前,通过更改列表中 Word 文档中的单词的字体颜色来突出显示。

def highlight_words(document, words):
    for paragraph in document.paragraphs:
        for run in paragraph.runs:
            for word in words:
                if word in run.text:
                    for txt in run._element.iter("t"):
                        if word in txt.text:
                            txt.text = txt.text.replace(word, '')
                            new_run = run._element
                            r = new_run.getparent()
                            rPr = r.get_or_add_rPr()
                            rPr.color = RGBColor(255, 0, 0)

这是高亮的相关函数。但是,它无法突出显示任何单词。我已经从聊天 gpt 和堆栈溢出中尝试了几种不同的方法,但每一种方法要么给出一个错误,要么突出显示整个句子或段落,要么给我提供了冗长的内容。

def analyze(filename):
    causal_words_to_highlight = ["and", "then"]  # Hardcoded words to highlight
    weak_words_to_highlight = ["got", "gots", "put", "really", "very", "said", "good", "bad", "go", "going", "went", "come", "comes", "came", "say", "said", "get", "got", "see", "saw", "nice", "mean", "pretty", "ugly", "big", "a lot", "fun", "well", "little", "fast", "slow", "big", "small", "interesting", "fetid", "really"]
    there_words_to_highlight = ["There is", "There was", "There are", "There were"]
    story = import_story(filename)
    if story is not None:
        doc = Document()

        # Add each paragraph to the new document and highlight words
        for paragraph_text in story.split("\n"):
            paragraph = doc.add_paragraph()
            paragraph.add_run(paragraph_text)

        # Highlight specific words in the document
        words_to_highlight = causal_words_to_highlight + weak_words_to_highlight + there_words_to_highlight + ["just"]
        highlight_words(doc, words_to_highlight)

        # Save the modified document
        doc.save(f"{filename[:-5]}_highlighted.docx")

这是分析功能的相关部分。

感谢所有帮助

python python-docx
1个回答
0
投票

我解决了,修改一下就好了

highlight_words

def highlight_words(document, words):
    for paragraph in document.paragraphs:
        for run in paragraph.runs:
            for word in words:
                if word in run.text:
                    run.font.color.rgb = RGBColor(255, 0, 0)
© www.soinside.com 2019 - 2024. All rights reserved.