提取文本我有这样的文字:与LXML
INTRODUCTION
This is a test document for xml.
I need to extract this sentence.
Conclusion
It should hopefully..
线I need to extract this sentence.
是斜体。该文件的XML是什么样子:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n
<w:document
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
mc:Ignorable="w14 w15 wp14">
<w:body>
<w:p w:rsidR="00470EEF" w:rsidRDefault="00456755">
<w:pPr>
<w:rPr>
<w:b/>
</w:rPr>
</w:pPr>
<w:r w:rsidRPr="00456755">
<w:rPr>
<w:b/>
</w:rPr>
<w:t>INTRODUCTION</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00456755" w:rsidRPr="00B042E3" w:rsidRDefault="00456755">
<w:pPr>
<w:rPr>
<w:color w:val="FFFF00"/>
</w:rPr>
</w:pPr>
<w:r w:rsidRPr="00B042E3">
<w:rPr>
<w:color w:val="FFFF00"/>
</w:rPr>
<w:t>This is a test document for xml.</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00456755" w:rsidRDefault="00E971E1">
<w:r>
<w:rPr>
<w:i/>
</w:rPr>
<w:t>I need to extract this sentence.</w:t>
</w:r>
<w:bookmarkStart w:id="0" w:name="_GoBack"/>
<w:bookmarkEnd w:id="0"/>
</w:p>
<w:p w:rsidR="00456755" w:rsidRDefault="00456755"/>
<w:p w:rsidR="00456755" w:rsidRDefault="00456755">
<w:pPr>
<w:rPr>
<w:b/>
</w:rPr>
</w:pPr>
<w:r w:rsidRPr="00456755">
<w:rPr>
<w:b/>
</w:rPr>
<w:t>Conclusion</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00456755" w:rsidRPr="00456755" w:rsidRDefault="00456755">
<w:r w:rsidRPr="00456755">
<w:t>It should hopefully</w:t>
</w:r>
<w:r>
<w:t>..</w:t>
</w:r>
</w:p>
<w:sectPr w:rsidR="00456755" w:rsidRPr="00456755">
<w:pgSz w:w="11906" w:h="16838"/>
<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>
<w:cols w:space="708"/>
<w:docGrid w:linePitch="360"/>
</w:sectPr>
</w:body>
</w:document>
我想:
tree = ET.parse(doc_xml)
[b.tag for b in tree.iterfind(".//i")]
以上返回一个空列表。
我搜索了很多,但无法弄清楚如何做到这一点,因为文本包含在<w:i/>
。我看到这个question这是用BeautifulSoup轻松完成的。
编辑:这不完全相关,但这是一个ElementTree方法来提取所有文本。
w = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
for p in source.findall('.//{' + w + '}p'):
print ''.join(t.text for t in p.findall('.//{' + w + '}t'))
您可能需要通过绑定前缀(如“w”)来告诉它使用URI为“http://schemas.openxmlformats.org/wordprocessingml/2006/main”的命名空间。 – LarsH 2014-09-22 05:51:38
是的,我已经这样做了,甚至通过'p'标签和't'标签提取所有文本。 – 2014-09-22 05:53:57
请告诉我们您已经完成了什么。你展示的Python没有表明任何名称空间的使用。 – LarsH 2014-09-22 05:54:55