繁体   English   中英

如何使用 Python 从 doc/docx 文件中提取数据

[英]How do I extract data from a doc/docx file using Python

我知道那里有类似的问题,但我找不到能回答我祈祷的东西。 我需要的是一种从 MS-Word 文件访问某些数据并将其保存在 XML 文件中的方法。 阅读python-docx并没有帮助,因为它似乎只允许一个人写入 word 文档,而不是阅读。 准确地展示我的任务(或者我选择如何完成我的任务):我想在文档中搜索关键字或短语(文档包含表格)并从关键字/短语所在的表格中提取文本数据成立。 有人有什么想法吗?

docx 是一个包含文档 XML 的 zip 文件。 您可以打开 zip,阅读文档并使用 ElementTree 解析数据。

这种技术的优点是您不需要安装任何额外的 python 库

import zipfile
import xml.etree.ElementTree

WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
PARA = WORD_NAMESPACE + 'p'
TEXT = WORD_NAMESPACE + 't'
TABLE = WORD_NAMESPACE + 'tbl'
ROW = WORD_NAMESPACE + 'tr'
CELL = WORD_NAMESPACE + 'tc'

with zipfile.ZipFile('<path to docx file>') as docx:
    tree = xml.etree.ElementTree.XML(docx.read('word/document.xml'))

for table in tree.iter(TABLE):
    for row in table.iter(ROW):
        for cell in row.iter(CELL):
            print ''.join(node.text for node in cell.iter(TEXT))

请参阅我的 stackoverflow 回答如何使用 Python 读取 MS-Word 文件中表格的内容? 有关更多详细信息和参考。

在回答下面的评论时,图像的提取方式并不明确。 我创建了一个空的 docx 并在其中插入了一个图像。 然后我打开 docx 文件作为 zip 存档(使用 7zip)并查看 document.xml。 所有图像信息都作为属性存储在 XML 中,而不是像文本那样存储在 CDATA 中。 因此,您需要找到您感兴趣的标签并提取您要查找的信息。

例如添加到上面的脚本中:

IMAGE = '{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}' + 'docPr'

for image in tree.iter(IMAGE):
    print image.attrib

输出:

{'id': '1', 'name': 'Picture 1'}

我不是 openxml 格式的专家,但我希望这会有所帮助。

我确实注意到 zip 文件包含一个名为 media 的目录,其中包含一个名为 image1.jpeg 的文件,其中包含我的嵌入图像的重命名副本。 您可以在 docx zipfile 中环顾四周以调查可用的内容。

使用 python-docx 在文档中搜索

# Import the module
from docx import *

# Open the .docx file
document = opendocx('A document.docx')

# Search returns true if found    
search(document,'your search string')

您还有一个获取文档文本的函数:

https://github.com/mikemaccana/python-docx/blob/master/docx.py#L910

# Import the module
from docx import *

# Open the .docx file
document = opendocx('A document.docx')
fullText=getdocumenttext(document)

使用https://github.com/mikemaccana/python-docx

pywin32 似乎可以解决问题。 您可以遍历文档中的所有表格以及表格中的所有单元格。 获取数据有点棘手(必须省略每个条目的最后 2 个字符),但除此之外,它是一个十分钟的代码。 如果有人需要更多详细信息,请在评论中说明。

具有图像提取功能的更简单的库。

pip install docx2txt


然后使用以下代码读取 docx 文件。

import docx2txt
text = docx2txt.process("file.docx")

使用 python 从 doc/docx 文件中提取文本

import os
import docx2txt
from win32com import client as wc

def extract_text_from_docx(path):
    temp = docx2txt.process(path)
    text = [line.replace('\t', ' ') for line in temp.split('\n') if line]
    final_text = ' '.join(text)
    return final_text

def extract_text_from_doc(doc_path):
    w = wc.Dispatch('Word.Application')
    doc = w.Documents.Open(file_path)
    doc.SaveAs(save_file_name, 16)
    doc.Close()
    w.Quit()
    joinedPath = os.path.join(root_path,save_file_name)
    text = extract_text_from_docx(joinedPath)
    return text

def extract_text(file_path, extension):
    text = ''
    if extension == '.docx':
       text = extract_text_from_docx(file_path)
    else extension == '.doc':
       text = extract_text_from_doc(file_path)
return text

file_path = #file_path with doc/docx file
root_path = #file_path where the doc downloaded
save_file_name = "Final2_text_docx.docx"
final_text = extract_text(file_path, extension)
print(final_text)

暂无
暂无

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

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