我如何不收到“ nonetype”错误消息

时间:2020-04-15 16:23:27

标签: python

下面,我附加了我的XML文档和我要为其编写的代码。我要打印每个同事的姓名,专业,副修和毕业年份。由于并非每个工作人员都有未成年人,所以我想打印“ N / A”,所以我不断收到此错误消息:minor = worker.find('minor')。text或“ n / a” AttributeError:“ NoneType”对象没有属性“ text” 这是我的XML文档:

<?xml version = "1.0" encoding = "UTF-8"?>
<workers>
    <worker>
        <name>Susan</name>
        <major>Sociology</major>
        <minor>Spanish</minor>
        <gradyear>2014</gradyear>
    </worker>
    <worker>
        <name>Jeremy</name>
        <major>Neuroscience</major>
        <gradyear>2016</gradyear>
    </worker>
    <worker>
        <name>Leigh</name>
        <major>Kinesiology</major>
        <minor>Business Administration</minor>
        <gradyear>2016</gradyear>
    </worker>
    <worker>
        <name>Kenny</name>
        <major>Biochemistry</major>
        <gradyear>2012</gradyear>
    </worker>
    <worker>
        <name>Sarena</name>
        <major>Finance</major>
        <gradyear>2018</gradyear>
    </worker>
</workers>

这是我编写的代码:

import xml.etree.ElementTree as ET
tree = ET.parse('coworkers.xml')
root = tree.getroot()
for student in root.findall('workers'):
        name = worker.find('name').text
        major = worker.find('major').text
        minor = worker.find('minor').text or "n/a"
        gradyear = worker.find('gradyear').text
        print("Workers:", name, "Major:", major, "Minor:", minor, "Graduation year:", gradyear)

2 个答案:

答案 0 :(得分:0)

您需要测试是否首先获得了元素

import xml.etree.ElementTree as ET
tree = ET.parse('hw7.xml')
root = tree.getroot()
for student in root.findall('student'):
        name = student.find('name').text
        major = student.find('major').text
        minor_elem = student.find('minor')
        if minor_elem:
            minor = minor_elem.text 
        else:
            minor = "n/a"
        gradyear = student.find('gradyear').text
        print("Student:", name, "Major:", major, "Minor:", minor, "Graduation year:", gradyear)

或根据需要使用异常处理程序

import xml.etree.ElementTree as ET
tree = ET.parse('hw7.xml')
root = tree.getroot()
for student in root.findall('student'):
        name = student.find('name').text
        major = student.find('major').text
        try:
            minor = student.find('minor').text
        except AttributeError:
            minor = "n/a"
        gradyear = student.find('gradyear').text
        print("Student:", name, "Major:", major, "Minor:", minor, "Graduation year:", gradyear)

答案 1 :(得分:0)

该异常表明某些<student>元素甚至没有<minor>属性,这意味着student.find('minor')None,那么您正在尝试调用.text None上的属性。因此,最好的方法是使用if-else或try-except块,如下所示。

# replace this
minor = student.find('minor').text or "n/a" 

# with option 1
minor = student.find('minor').text if student.find('minor') else "n/a"

OR

# with option 2
try:
    minor = student.find('minor').text
except AttributeError as err:
    minor = "n/a"
    print(f"{name} has no attribute 'minor', because {err} occured") # this is optional though