2017-11-20 25 views
1

私は先生です。私が割り当てたエッセイにコメントしたすべての生徒のリストと、彼らが言ったことがあります。 Drive APIのものは私にとっては挑戦的でしたが、私はそれらをzipとしてダウンロードしてXMLを解析できると考えました。DOCXのコメントを抽出する

コメントはw:commentタグで、w:tのコメントテキストにタグ付けされています。それは簡単なはずですが、XML(etree)が私を殺しています。チュートリアル(公式のPythonドキュメント)を経由して

:この中に結果の

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'} 

そしてこの後、私は完全にしています

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

その後、私はこれを行います立ち往生した。私はelement.get()element.findall()を試したことがありません。値('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val')をコピー/ペーストしても、私はNoneを受け取ります。

誰でも手助けできますか?

+0

要素のテキストコンテンツが 'text'財産です。 'print(c.text)'は興味のあるものを生成しますか? – mzjn

+0

'A = tree.get( '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}ヴァル') プリント(a.text)cについて' AttributeError' 'で' 結果子供の場合: print(c.text) ' コメントの結果!私は他のフィールドにどのようにアクセスするのか知っていますか? –

答えて

1

あなたは、OOXMLがそのような複雑なフォーマットであると考えています。ここで

は、XPathを経由してDOCXファイルのコメントにアクセスする方法を示すいくつかのサンプルPythonコードです:

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

答えと称賛!ありがとうございました! –

関連する問題