繁体   English   中英

使用 python 从 .docx 文件中提取特定表和图像

[英]Extract a specific table and image from .docx file using python

我正在尝试从 word 文档中提取一个特定的表格,该表格位于标题“缩写列表”之后,而图像则位于 .docx 文件中的标题“图形研究”之后。 我已经能够使用 python-docx 代码提取标题,但是如何使用标题或它们的 position 解析文档以检索图像和表格。在美丽的汤中,我正在使用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)

你可以做:

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

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

您可以使用 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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM