2014-11-04 42 views
1

解析XML文件时,我有这样的XML文件:获得NoneType错误在Python

<dep type="nsubj"> 
      <governor idx="7">open</governor> 
      <dependent idx="5">it</dependent> 
      </dep> 
      <dep type="aux"> 
      <governor idx="7">open</governor> 
      <dependent idx="6">will</dependent> 
      </dep> 
      <dep type="ccomp"> 
      <governor idx="3">announced</governor> 
      <dependent idx="7">open</dependent> 
      </dep> 

我想分析它,并提取深型,即像nsubj,AUX,CCOMP等我” m这样做:

file_list=[] 
with open(xml_file) as f: 
    page = f.read() 
f.close() 
soup = BeautifulSoup(page,"xml") 
for types in soup.find_all('dep'): 
    file_list.append(types.string.strip()) 
print file_list 

但是,我得到NoneType错误。为什么这样?

编辑:

回溯:

Traceback (most recent call last): 
    File "/Users/akritibahal/Downloads/stanford-corenlp-2012-07-09/testing.py", line 103, in <module> 
    main() 
    File "/Users/akritibahal/Downloads/stanford-corenlp-2012-07-09/testing.py", line 102, in main 
    extract_top_dependencies('/Users/akritibahal/Downloads/stanford-corenlp-2012-07-09/test') 
    File "/Users/akritibahal/Downloads/stanford-corenlp-2012-07-09/testing.py", line 80, in extract_top_dependencies 
    file_list.append(types.string.strip()) 
AttributeError: 'NoneType' object has no attribute 'strip' 

EDIT2:

我认为它是怎么把我怎么一直在做的XML解析是它的<>这些标记之间的读取。但对于dep,我想提取type =中的内容,并且打开和关闭标记之间没有任何内容。怎么做?

+0

请编辑完整的回溯,你得到的NoneType错误到你的问题。 – Marius 2014-11-04 04:01:58

+0

哪条线导致此? – Eric 2014-11-04 04:02:52

回答

0

根据您的编辑(您的原始for声明中的名称types),您似乎位于标记属性之后而不是字符串之后。要访问标记属性,尝试一些大意如下代替:

>>> xml = """<root><dep type="nsubj"> 
      <governor idx="7">open</governor> 
      <dependent idx="5">it</dependent> 
      </dep> 
      <dep type="aux"> 
      <governor idx="7">open</governor> 
      <dependent idx="6">will</dependent> 
      </dep> 
      <dep type="ccomp"> 
      <governor idx="3">announced</governor> 
      <dependent idx="7">open</dependent> 
      </dep></root>""" 
>>> soup = BeautifulSoup(xml) 
>>> for dep in soup.find_all('dep'): 
    print dep.attrs.get('type') 

nsubj 
aux 
ccomp 

换句话说,我想你想这样的事情,而不是:

>>> for dep_elem in soup.find_all('dep'): 
     type_ = dep_elem.attrs.get('type') 
     if type_: # be sure type_ is not a NoneType 
      file_list.append(type_.strip()) 

参见文档here

0

取出

f.close() 

线!它在使用with open()语法时自动完成,名称f仅在with块内有效。

+0

我认为这是因为我一直在做XML解析是它读取<>这些标签之间。但对于dep,我想提取type =中的内容,而标签之间没有任何内容。怎么做? – 2014-11-04 04:14:56