如何解析nonetype对象在python 2.7中没有属性编码错误

时间:2016-07-04 07:00:34

标签: python xml unicode

我正在运行以下代码:

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对象没有属性编码”。如何解决?

1 个答案:

答案 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')