提取.docx数据,图像和结构

时间:2019-08-19 09:56:35

标签: python python-docx

好,

我有一个任务需要提取文档模板的特定部分(出于自动化目的)。虽然我能够在遍历期间遍历并知道文档的当前位置(通过检查正则表达式,关键字等),但无法提取:

  1. 文档的结构
  2. 检测文本之间的图像

enter image description here

例如,我能否获得下面文档结构的数组?

['Paragraph1','Paragraph2','Image1','Image2','Paragraph3','Paragraph4','Image3','Image4']

我当前的实现如下所示:

from docx import Document

document = docx.Document('demo.docx')

text = []

for x in document.paragraphs:
    if x.text != '':
        text.append(x.text)

使用上面的代码,我能够从文档中获取所有的Text数据,但是我无法检测到文本类型(Header或Normal),并且无法检测到任何图像。我目前正在使用python-docx。

我的主要问题是获取图像在文档中的位置(即在段落之间),以便我可以使用提取的文本和图像重新创建另一个文档。此任务要求我知道图像在文档中的位置以及在新文档中的图像插入位置。

非常感谢您的帮助,谢谢:)

1 个答案:

答案 0 :(得分:0)

要提取段落的结构和标题,可以使用 python-docx 中的内置对象。检查此代码。

from docx import Document
document = docx.Document('demo.docx')
text  = []
style = []
for x in document.paragraphs:
    if x.text != '':
        style.append(x.style.name)
        text.append(x.text)

使用x.style.name可以获取文档中文本的样式。

您无法在python-docx中获取有关图像的信息。为此,您需要解析xml。检查XML输出,

for elem in document.element.getiterator():
    print(elem.tag)

让我知道您是否还有其他需要。

要提取图像名称及其位置,请使用它。

tags = []
text = []
for t in doc.element.getiterator():
    if t.tag in ['{http://schemas.openxmlformats.org/wordprocessingml/2006/main}r', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t','{http://schemas.openxmlformats.org/drawingml/2006/picture}cNvPr','{http://schemas.openxmlformats.org/wordprocessingml/2006/main}drawing']:
        if t.tag == '{http://schemas.openxmlformats.org/drawingml/2006/picture}cNvPr':
            print('Picture Found: ',t.attrib['name'])
            tags.append('Picture')
            text.append(t.attrib['name'])
        elif t.text:
            tags.append('text')
            text.append(t.text)

您可以从文本列表中检查上一个和下一个文本,并从标签列表中检查它们的标签。

相关问题