【问题标题】:Python-docx - check if text in table has hidden attribute appliedPython-docx - 检查表中的文本是否应用了隐藏属性
【发布时间】:2021-10-12 12:18:11
【问题描述】:

我是 Python 新手,我正在尝试检查 docx 文件以查找表中应用了隐藏属性的文本。如果为真,那么我想忽略该隐藏文本并替换与我的正则表达式匹配的任何其他文本。

在我添加 if i.font.hidden == True: 条件似乎不正确之前,一切都很好(更换工作正常)。

我得到的错误: AttributeError: 'int' 对象没有属性 'font'

这是我的代码:

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

【问题讨论】:

    标签: python hidden python-docx


    【解决方案1】:

    无需按索引访问运行;您可以直接迭代它们:

    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')
    

    【讨论】:

    • 谢谢,它也可以。我没有注意到这种方法节省了执行时间,但它肯定更简单,因为代码少了一点。
    【解决方案2】:

    在您的情况下,i 只是一个整数,因为您正在迭代整数列表。

    我猜你需要类似的东西:

    if inline[i].font.hidden == True:
        *do stuff*
    

    【讨论】:

      猜你喜欢
      • 2012-05-06
      • 2022-01-24
      • 2019-01-03
      • 2019-04-07
      • 2023-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多