我正在运行以下代码:
from __future__ import unicode_literals
import xml.etree.ElementTree as ET
tree = ET.parse('dblp_16.xml')
root = tree.getroot()
f = open('hi', 'w')
for country in root.findall('article'):
rank = country.find('year').text
name = country.find('title')
if(int(rank)>2009):
f.write(name.text.encode('utf8'))
f.write(':')
auth = country.findall('author')
for a in auth:
#print str(a)
f.write(a.text.encode('utf8'))
f.write(',')
f.write('\n')
运行上述代码时出错:“nonetype对象没有属性编码”。如何解决?
答案 0 :(得分:2)
只需查看if name.text is not None
from __future__ import unicode_literals
import xml.etree.ElementTree as ET
tree = ET.parse('dblp_16.xml')
root = tree.getroot()
f = open('hi', 'w')
for country in root.findall('article'):
rank = country.find('year').text
name = country.find('title')
if not name.text:
continue
if(int(rank)>2009):
f.write(name.text.encode('utf8'))
f.write(':')
auth = country.findall('author')
for a in auth:
#print str(a)
f.write(a.text.encode('utf8'))
f.write(',')
f.write('\n')