Python解析xml文件

时间:2016-04-10 01:25:11

标签: python xml

我需要解析一个xml文件,哪种方法最适合我的情况。 beautifulsoup4,ElementTree等等,它是一个非常大的文件。 我有windows 10 64bit运行python 2.7.11 32bit

xml文件: http://pastebin.com/jTDRwCZr

我试图从xml文件中获取此输出,它包含使用" div xml:lang ="英语" "对于英语。任何帮助我如何使用beautifulsoup与lxml来实现这一目标?谢谢你的时间。

<tt xmlns="http://www.w3.org/2006/04/ttaf1"     xmlns:tts="http://www.w3.org/2006/04/ttaf1#styling">
<head>
<styling>
<style id="1"  tts:textOutline='#000000 2px 2px'  tts:color="white"/>
</styling>
</head>
<body>
<div xml:lang="English">
<p begin="00:00:28.966" end="00:00:31.385" style="1">
text text text...
</p>
</div>
</body>
</tt>

1 个答案:

答案 0 :(得分:0)

您链接到的文件不是那么大,您需要担心解析和处理它的替代方法。

假设您尝试删除所有非英语语言div,您可以使用BeautifulSoup执行此操作:

from bs4 import BeautifulSoup

with open('input.xml') as infile:
    soup = BeautifulSoup(infile, 'lxml')
    for e in soup.find_all('div', attrs={'xml:lang': lambda value: value != 'English'}):
        _ = e.extract()

with open('output.xml', 'w') as outfile:
    outfile.write(soup.prettify(soup.original_encoding))

在上面的代码中,soup.find_all()会找到div属性不是xml:lang的所有'English'。然后使用extract()删除匹配的元素。最后,使用与输入相同的编码将结果文档写入新文件(否则它将默认为UTF-8)。

相关问题