分享
三行代码  ›  专栏  ›  技术社区  ›  richylyq

是否可以将这些冗长的代码更改为递归函数?

  •  0
  • richylyq  · 技术社区  · 4 天前

    我试图从.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工作正常,因为我知道会有多少嵌套表。

    1 回复  |  直到 4 天前
        1
  •  1
  •   Boendal    4 天前

    根据您给出的描述和代码片段,应该可以:

    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)