Search code examples
pythonms-wordhighlightpython-docx

NameError: name 'WD_COLOR_INDEX' is not defined while using python-docx


I have been trying to find the highlight colors in an MS Word document using python-docx (python-docx-0.8.6, python 2.7, 32 bit) and process each piece of the text based on its highlight color.

Following the documentation, I tried to import/use WD_COLOR_INDEX, but can't seem to locate it.

from docx.enum import *

if (doc.paragraphs[i].runs[j].font.highlight_color == WD_COLOR_INDEX.YELLOW): 
    #do the appropriate thing for the yellow-highlighted text

How do I import the color index?


Solution

  • This enumeration is related to text, so is found in the docx.enum.text module:

    from docx.enum.text import WD_COLOR_INDEX
    

    It also has an alias (for more compact expression), so you can use this instead:

    from docx.enum.text import WD_COLOR
    

    Which makes each reference shorter, e.g. WD_COLOR.YELLOW.