Skip to main content
 首页 » 编程设计

python之提取 DOCX 注释

2025年05月04日13davidwang456

我是一名教师。我想要一份对我布置的论文发表评论的所有学​​生的名单,以及他们所说的内容。 Drive API 的东西对我来说太具有挑战性了,但我想我可以将它们下载为 zip 文件并解析 XML。

评论被标记在w:comment 标签中,w:t 用于评论文本,.这应该很容易,但 XML (etree) 太让我难受了。

通过教程(和官方 Python 文档):

z = zipfile.ZipFile('test.docx') 
x = z.read('word/comments.xml') 
tree = etree.XML(x) 

然后我这样做:

children = tree.getiterator() 
for c in children: 
    print(c.attrib) 

结果是:

{} 
{'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}author': 'Joe Shmoe', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}id': '1', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}date': '2017-11-17T16:58:27Z'} 
{'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rsidR': '00000000', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rsidDel': '00000000', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rsidP': '00000000', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rsidRDefault': '00000000', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rsidRPr': '00000000'} 
{} 
{'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': '0'} 
{'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': '0'} 
{'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': '0'} 

在这之后我完全被困住了。我试过 element.get() 和 element.findall() 但没有成功。即使我复制/粘贴值 ('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val'),我也得到 None 作为返回.

有人能帮忙吗?

请您参考如下方法:

考虑到 OOXML 是一种如此复杂的格式,您已经走得太远了。

下面是一些示例 Python 代码,展示了如何通过 XPath 访问 DOCX 文件的注释:

from lxml import etree 
import zipfile 
 
ooXMLns = {'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'} 
 
def get_comments(docxFileName): 
  docxZip = zipfile.ZipFile(docxFileName) 
  commentsXML = docxZip.read('word/comments.xml') 
  et = etree.XML(commentsXML) 
  comments = et.xpath('//w:comment',namespaces=ooXMLns) 
  for c in comments: 
    # attributes: 
    print(c.xpath('@w:author',namespaces=ooXMLns)) 
    print(c.xpath('@w:date',namespaces=ooXMLns)) 
    # string value of the comment: 
    print(c.xpath('string(.)',namespaces=ooXMLns))