Search code examples
pythonhiddenpython-docx

Python-docx - check if text in table has hidden attribute applied


I am new to Python and I am trying to check docx file for texts in table that have hidden attribute applied to them. If True, then I want to ignore that hidden text and replace any other text that matches my regex.

The thing is everything been good (replacement is working) until I added if i.font.hidden == True: condition thata seems to be incorrect.

The error I am getting: AttributeError: 'int' object has no attribute 'font'

This is the code I have:

for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for p in cell.paragraphs:
                        if True:
                            inline = p.runs
                            for i in range(len(inline)):
                                if True:
                                    if i.font.hidden == True:
                                        continue
                                    else:
                                        text = inline[i].text.replace(regx, 'Abcd')
                                           
                                        inline[i].text = text

Solution

  • No need to access runs by index; you can iterate those directly:

    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for p in cell.paragraphs:
                    for run in p.runs:
                        if not run.font.hidden:
                            run.text = run.text.replace(regx, 'Abcd')