Ste*_*anu 4 python ms-word doc docx
我知道那里有类似的问题,但我找不到能回答我祈祷的事情.我需要的是一种从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))
Run Code Online (Sandbox Code Playgroud)
请参阅我的stackoverflow回答如何使用Python读取MS-Word文件中的表的内容?了解更多细节和参考.
使用 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')
Run Code Online (Sandbox Code Playgroud)
您还有一个获取文档文本的函数:
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)
Run Code Online (Sandbox Code Playgroud)
使用https://github.com/mikemaccana/python-docx
看来 pywin32 可以解决这个问题。您可以遍历文档中的所有表格以及表格内的所有单元格。获取数据有点棘手(必须省略每个条目的最后 2 个字符),但除此之外,这是一个十分钟的代码。如果有人需要更多详细信息,请在评论中说明。