Python start事件读取xml Ignoring item: 'NoneType' object,ignoringnonetype,要读取一个xml文件中每
Python start事件读取xml Ignoring item: 'NoneType' object,ignoringnonetype,要读取一个xml文件中每
要读取一个xml文件中每个item节点的review_id、summary等的子结点,样例如下:
<item><review_id>0095693</review_id><summary>书本内容</summary><polarity>P</polarity><text>书本的内容很好,对我很有帮助,就是字体的颜色是紫色的,看就了会觉得不清晰。</text><category>book</category></item>
完整例子可以从这里下载。编程环境为Mac 10.9.2,Python 2.7.6,代码如下:
import sysimport osfrom xml.etree.ElementTree import iterparse, tostringdef count_pos_neg(itemfile): pos_count = 0 neg_count = 0 try: for event, elem in iterparse(itemfile, events=["start",]): if elem.tag == "item": try: if processItem(elem)['polarity'] == "P": pos_count += 1 else: neg_count += 1 except Exception, e: print >> sys.stderr, "Ignoring item: %s" % e elem.clear() except SyntaxError, se: print >> sys.stderr, se return pos_count, neg_countdef processItem(item): """ Process a review. Implement custom code here. Use 'item.find('tagname').text' to access the properties of a review. """ category = item.find("category").text polarity = item.find("polarity").text text = item.find("text").text summary = item.find("summary").text return {'polarity':polarity, 'summary':summary, 'text':text, 'category':category }if __name__ == "__main__": pc, nc = count_pos_neg(itemfile)
问题在于,每碰到第55个item节点,就会发生一次AttruibuteError,错误信息为
Ignoring item: 'NoneType' object has no attribute 'text'
我在使用evens=('end',)进行解析时,没有发生错误。这是否说明之前的错误与使用start解析有关?
文档说:
start 事件发生时这个元素的子元素还没有解析,所以你应该用 end 事件。
编橙之家文章,
相关内容
- Python对XML大文件数据去重什么方法好,pythonxml文件数据
- Python项目运行找不到模块问题,python模块,背景在subli
- 求Python正则匹配高手帮我查下源码问题在哪里,python源
- 请问Flask开发应用nginx与uwsgi应该如何部署,flasknginx,使
- 想调用pymysql返回值中varchar内容怎么写,pymysqlvarchar,m
- Python有与reinterpret_cast类同的机制吗,,嗯这里&ldquo
- 请python高手帮我看看这段python代码中函数setter的用意,
- apache运行webpy项目遇到换行符无故增加的恼人问题,a
- Pyramid框架对于Audit审计功能应用参考书箱有什么?,py
- python3版本 tkinter gui写出来的程序最小化到系统托盘,
评论关闭