今天查找了一些python对xml文档的处理,之前用过java对xml文件进行处理,这个以后应该还会用到,这里先记录一下最基本的用到的操作。
要解析的xml文档格式为
可以先用notepad进行一些处理。
代码为:
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
tree = ET.parse('test_new1.xml')
root = tree.getroot()
i = 0
for child in root[0:10]:
title = child.findall('news_title')
context = child.findall('news_body')
#这里是测试,一共有1万篇文章,所以这样命名
filename = '%05d.txt'%i
#title是个列表,用text可以获得内容
t = title[0].text + ' ' + context[0].text.replace("\t"," ").replace("\n","")
t = t.encode("utf-8")
with open(filename,"w") as f:
f.write(t)
i += 1
#print title[0].text + ' ' + context[0].text
其实也是在网上看到别人写的东西,进行了模仿,改成适用自己的代码。
try语句是引入处理xml的包,尽量用C语言编译的import xml.etree.cElementTree as ET要快一些,而且占用内存少
并且import xml.etree.cElementTree as ET并不是很安全。
要有一点要注意的是python在处理中文文档的时候,写入数据要将数据以‘utf-8’的形式编码。
之后就可以做一些分词,文本分类等任务了