2015-10-27 118 views
0

我正在通过一本书(Python for Data Analysis),它有下面的代码:运行循环时出现'没有这样的孩子:pyval'错误。我是否有语法错误或类似的东西'no such child:pyval“error

from lxml import objectify 
path = 'Performance_MNR.xml' 
parsed = objectify.parse(open(path)) 
root = parsed.getroot() 
data = [] 
skip_fields = ['PARENT_SEQ', 'INDICATOR_SEQ', 'DESIRED_CHANGE', 'DECIMAL_PLACES'] 
for elt in root.INDICATOR: 
    el_data = {} 
    for child in elt.getchildren(): 
     if child.tag in skip_fields: 
      continue 
     el_data[child.tag] = child.pyval 
     data.append(el_data) 

回溯如下:?

AttributeError       Traceback (most recent call last) 
<ipython-input-17-88720283f598> in <module>() 
     4  if child.tag in skip_fields: 
     5   continue 
----> 6  el_data[child.tag] = child.pyval 
     7 data.append(el_data) 
     8 

lxml.objectify.pyx in lxml.objectify.ObjectifiedElement.__getattr__ (src/lxml/lxml.objectify.c:3497)() 

lxml.objectify.pyx in lxml.objectify._lookupChildOrRaise (src/lxml/lxml.objectify.c:5947)() 

AttributeError: no such child: pyval 

回答

0

试试这个:

for elt in root: 
el_data = {} 
for child in elt.getchildren(): 
    if child.tag in skip_fields: 
     continue 
    el_data[child.tag] = child.pyval 
    data.append(el_data) 
0

Tr的y将'pyval'改为'text',那样会好的。

data=[] 
skip_fields=['PARENT_SEQ','INDICATOR_SEQ','DESIRED_CHANGE','DECIMAL_PLACES'] 
for elt in root.INDICATOR: 
    el_data={} 
    for child in elt.getchildren(): 
     if child.tag in skip_fields: 
      continue 
     el_data[child.tag]=child.text 
    data.append(el_data) 
1

我也在读这本书,并遇到同样的问题。这对我有效。

skip_fields = ['PARENT_SEQ', 'INDICATOR_SEQ', 
      'DESIRED_CHANGE', 'DECIMAL_PLACES', 'YEAR'] 
相关问题