【问题标题】:Possible to change these lengthy codes to a recursion function?可以将这些冗长的代码更改为递归函数吗?
【发布时间】:2020-05-01 23:26:27
【问题描述】:

我正在尝试从 .docx 文档中的表(也包括嵌套表)中获取数据。但是我当前的代码看起来像:

def pctnt():
    tables = doc.tables
    for table in tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    print(paragraph.text)
                for table in cell.tables:
                    for row in table.rows:
                        for cell in row.cells:
                            for paragraph in cell.paragraphs:
                                print(paragraph.text)
                            for table in cell.tables:
                                for row in table.rows:
                                    for cell in row.cells:
                                        for paragraph in cell.paragraphs:
                                            print(paragraph.text)

它适用于我当前的 .docx,因为我知道会有多少嵌套表。

但是,当我有其他文档进入时,情况并非如此,因此我需要一种方法来从嵌套表中检索数据,无论文档中有多少。

基于@Boendal 给出的解决方案的新问题

我是否可以将数据打印到列表中,以便我可以使用 pandas 打印美化表格或搜索特定表格单元格?

【问题讨论】:

  • 对我来说,您当前的代码似乎不需要您知道表的数量,因此它应该适用于任意数量的表。但也许我错过了什么?
  • 类似def iterate(thing): try: for item in thing: iterate(item); except TypeError: print(item)

标签: python recursion docx python-docx nested-table


【解决方案1】:

根据您提供的描述和您的代码片段,这应该可以工作:

def print_paragraphs(doc):
    for table in doc.tables:
        for row in table.row:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    print(paragraph.text)
                print_paragraphs(cell)

print_paragraphs(doc)

【讨论】:

  • 不错!这非常有效!我希望....经过测试,我认为这可以。谢谢@Boendal,您在几秒钟内就解决了它,而我正在寻找解决方案。
猜你喜欢
  • 2020-10-02
  • 2019-03-01
  • 1970-01-01
  • 2018-09-26
  • 2012-12-30
  • 2015-02-11
  • 1970-01-01
  • 2021-07-27
相关资源
最近更新 更多