我知道已经有类似的问题,但我找不到能够回答我的请求的东西。我需要一种方法来访问MS-Word文件中的特定数据并将其保存在XML文件中。 阅读 python-docx 没有帮助,因为它似乎只允许人们写入Word文档,而不是读取。 为了准确地展示我的任务(或者说我选择的方法):我想在文档中搜索关键字或短语(文档包含表格),并从找到关键字/短语的表格中提取文本数据。 有人有什么想法吗?
我知道已经有类似的问题,但我找不到能够回答我的请求的东西。我需要一种方法来访问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压缩文件中查看可用内容。
使用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')
# Import the module
from docx import *
# Open the .docx file
document = opendocx('A document.docx')
fullText=getdocumenttext(document)
pip install docx2txt
然后使用以下代码来读取docx文件。
import docx2txt
text = docx2txt.process("file.docx")
看起来 pywin32 可以解决问题。你可以遍历文档中的所有表格和表格内的所有单元格。获取数据有点棘手(需要省略每个条目的最后 2 个字符),但除此之外,只需十分钟代码即可完成。 如果有人需要更多细节,请在评论中说明。
使用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)