【问题标题】:Extract a specific table and image from .docx file using python使用 python 从 .docx 文件中提取特定的表格和图像
【发布时间】:2020-11-05 10:08:12
【问题描述】:

我正在尝试从 word 文档中提取一个特定的表格,该表格紧跟在 .docx 文件中的标题“缩写列表”和标题“图形研究”之后的图像。我已经能够使用 python-docx 代码提取标题,但是如何使用标题或其位置解析文档以检索图像和表格。在美丽的汤中,我使用if re.match("Graphical", img.previous_sibling.text) 搜索我的图像。我的 python docx 代码是:

from docx import *

document = Document('data/p21.docx')
document.save('test-new.docx')

for content in document.paragraphs:
    if content.style.name=='Heading 1' or content.style.name=='Heading 2' or content.style.name=='Heading 3':
        print (content.text)

【问题讨论】:

    标签: python docx python-docx


    【解决方案1】:

    你可以这样做:

    ...
    table = document.tables[table_number]
    ...
    

    其中 table_number 是文档中表格的编号,从 0 开始。(第一个表格是索引号 0,第二个是索引号 1,依此类推……)

    【讨论】:

    • 是的,这是我一直在使用的解决方法,但表格在不同文档中的不同位置,因此我需要为所有文档找到通用代码。有什么方法可以检测到标题之后的表格编号?
    【解决方案2】:

    您可以使用 xml 从 docx 文件中提取结构化信息。试试这个:

    doc = Document("file.docx")
    headings = [] #extract only headings from your code
    tables = [] #extract tables from your code
    tags = []
    all_text = []
    schema = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
    for elem in doc.element.getiterator():
        if elem.tag == schema + 'body':
            for i, child in enumerate(elem.getchildren()):
                if child.tag != schema + 'tbl':
                     node_text = child.text
                     if node_text:
                         if node_text in headings:
                             tags.append('heading')
                         else:
                             tags.append('text')
                         all_text.append(node_text)
                 else:
                     tags.append('table')
            break
    

    在上面的代码之后,您将获得标签列表,这些标签将显示文档标题、文本和表格的结构,然后您可以从列表中映射相应的数据。

    此外,检查标签列表中的数据以获取表格的标题。您可以迭代并获取标题所在的表格

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多