2015-10-27 219 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'] 
相關問題