提取DOCX评论

时间:2017-11-20 11:26:22

标签: python xml openxml google-docs docx

我是老师。我想要一份评论我所分配的论文的所有学生的名单,以及他们所说的内容。 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

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:4)

考虑到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))

答案 1 :(得分:2)

我使用Word Object Model从Word文档中提取带有回复的注释。可以在here上找到有关Comments对象的文档。本文档使用Visual Basic for Applications(VBA)。但是我可以在Python中使用这些功能,并稍加修改。 Word对象模型的唯一问题是我必须使用pywin32的win32com软件包,该软件包在Windows PC上可以正常运行,但是我不确定它是否可以在macOS上运行。

这是我用来提取带有相关回复的评论的示例代码:

    import win32com.client as win32
    from win32com.client import constants

    word = win32.gencache.EnsureDispatch('Word.Application')
    word.Visible = False 
    filepath = "path\to\file.docx"

    def get_comments(filepath):
        doc = word.Documents.Open(filepath) 
        doc.Activate()
        activeDoc = word.ActiveDocument
        for c in activeDoc.Comments: 
            if c.Ancestor is None: #checking if this is a top-level comment
                print("Comment by: " + c.Author)
                print("Comment text: " + c.Range.Text) #text of the comment
                print("Regarding: " + c.Scope.Text) #text of the original document where the comment is anchored 
                if len(c.Replies)> 0: #if the comment has replies
                    print("Number of replies: " + str(len(c.Replies)))
                    for r in range(1, len(c.Replies)+1):
                        print("Reply by: " + c.Replies(r).Author)
                        print("Reply text: " + c.Replies(r).Range.Text) #text of the reply
        doc.Close()

答案 2 :(得分:0)

感谢@kjhughes这个惊人的答案,它可以从文档文件中提取所有注释。我在该线程中面临与其他人一样的相同问题,以获取评论所涉及的文本。我以@kjhughes的代码为基础,并尝试使用python-docx解决此问题。所以这是我的看法。

样本文件。 enter image description here

我将提取注释和文档中引用的段落。

from docx import Document
from lxml import etree
import zipfile
ooXMLns = {'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
#Function to extract all the comments of document(Same as accepted answer)
#Returns a dictionary with comment id as key and comment string as value
def get_document_comments(docxFileName):
    comments_dict={}
    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:
        comment=c.xpath('string(.)',namespaces=ooXMLns)
        comment_id=c.xpath('@w:id',namespaces=ooXMLns)[0]
        comments_dict[comment_id]=comment
    return comments_dict
#Function to fetch all the comments in a paragraph
def paragraph_comments(paragraph,comments_dict):
    comments=[]
    for run in paragraph.runs:
        comment_reference=run._r.xpath("./w:commentReference")
        if comment_reference:
            comment_id=comment_reference[0].xpath('@w:id',namespaces=ooXMLns)[0]
            comment=comments_dict[comment_id]
            comments.append(comment)
    return comments
#Function to fetch all comments with their referenced paragraph
#This will return list like this [{'Paragraph text': [comment 1,comment 2]}]
def comments_with_reference_paragraph(docxFileName):
    document = Document(docxFileName)
    comments_dict=get_document_comments(docxFileName)
    comments_with_their_reference_paragraph=[]
    for paragraph in document.paragraphs:  
        if comments_dict: 
            comments=paragraph_comments(paragraph,comments_dict)  
            if comments:
                comments_with_their_reference_paragraph.append({paragraph.text: comments})
    return comments_with_their_reference_paragraph
if __name__=="__main__":
    document="Hi this is a test.docx"
    print(comments_with_reference_paragraph(document))

示例文档的输出如下所示 enter image description here

我已经在段落级别执行了此操作。这也可以在python-docx运行级别上完成。 希望会对您有所帮助。