2014-03-31 97 views
1

我知道那里有类似的问题,但我找不到可以回答我的祈祷的东西。我需要的是从MS-Word文件访问某些数据并将其保存在XML文件中的方法。 阅读python-docx没有帮助,因为它似乎只允许一个人写入Word文档,而不是阅读。 准确地呈现我的任务(或我如何选择接近我的任务):我想在文档中搜索关键词或短语(文档包含表格),并从表格中提取关键词/短语被发现。 有人有什么想法吗?如何从Python使用doc/docx文件提取数据

+1

我不得不做类似于xls/xlsx文件的事情,但是这很容易,因为有openpyxl库,它允许用户使用Excel Spreadsheets来做很多事情。但似乎在Python中使用doc/docx文件的支持较少。 –

回答

0

似乎pywin32的伎俩。您可以迭代文档中的所有表格以及表格内的所有单元格。获取数据有点棘手(每个条目的最后2个字符必须省略),否则,这是一个10分钟的代码。 如果有人需要更多的细节,请在评论中说明。

+0

您是否可以发布一个简单的例子代码来做到这一点? (即,选择表并将内容读取到变量,例如)谢谢 – dasen

+0

@dasen [Here](http://stackoverflow.com/questions/31553179/writing-a-pandas-dataframe-to-a-word- document-table-via-pywin32) – dashesy

0

在文档中搜索与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

+0

如果您要使用docx抓取表格中的单元格,请确保您阅读以避免出现性能问题:https://github.com/python-openxml/python-docx/issues/174 – Soferio

1

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)) 

看到我的计算器答案How to read contents of an Table in MS-Word file Using Python?更多的细节和引用。

+0

请不要发布链接只回答其他Stack Exchange问​​题。相反,在这里包括答案的重要部分,并*定制这个具体问题的答案。* – JAL

相关问题