为 docx 中的单词分配颜色代码并替换

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

您好,我想知道如何为生成的单词列表中的每个项目分配颜色代码?目前卡在 WD_COLOR_INDEX 上,这不允许我有效地循环列表中的项目。还有其他功能我可以使用吗?最终我想做一个替换功能,例如:

将“app”(以粉色突出显示)替换为“apple”(以绿色突出显示),因此将所有以粉色突出显示的单词替换为绿色。虽然我可以进行简单的单词替换,但突出显示可以让我在 Word 文档中找到该单词。

感谢我能得到的任何帮助,谢谢!

这是我尝试过的方法,它对我有用,只是它只有单一颜色:使用 python 突出显示 Word 文档中的某些单词

python replace docx highlight
1个回答
0
投票
from docx import Document
from docx.enum.text import WD_COLOR_INDEX

def highlight_words(document, word_list):
    for paragraph in document.paragraphs:
        for word in word_list:
            if word in paragraph.text:
                run = paragraph.runs
                i = 0
                while i < len(run):
                    if word in run[i].text:
                        run[i].font.highlight_color = WD_COLOR_INDEX.YELLOW  # Set highlight color to yellow
                        run[i].text = run[i].text.replace(word, f'[{word}]')  # Enclose the word in square brackets to mark it
                    i += 1

# Create a new Word document object
doc = Document()

# Generate a list of words
word_list = ['app', 'banana', 'orange']

# Insert some paragraphs and words into the document
doc.add_paragraph('This is an app')
doc.add_paragraph('I like to eat banana')
doc.add_paragraph('I have an orange')

# Call the function to set the highlight color and replacement mark for words
highlight_words(doc, word_list)

# Save the document
doc.save('highlighted.docx')

在此示例中,我们使用

highlight_words()
函数迭代文档的段落,并检查每个段落是否包含任何要突出显示的单词。如果找到匹配项,我们使用
run.font.highlight_color
属性设置单词的突出显示颜色,然后使用
run.text.replace()
函数将单词替换为方括号内的标记。最后,我们保存文档并得到一个带有突出显示的单词的Word文档。

您可以根据需要自定义颜色代码,并使用适当的条件设置不同的颜色和替换功能。

© www.soinside.com 2019 - 2024. All rights reserved.