在python中解析xml文件时出现非类型错误

2024-05-08 20:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的xml文件:

<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>

我想解析它并提取deep类型,例如nsubj、aux、ccomp等。我是这样做的:

^{pr2}$

但是,我得到了非类型错误。为什么会这样?在

编辑:

回溯:

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'

编辑2:

我想这是因为我一直在进行xml解析,因为它读取这些标记之间的内容。但是对于dep,我想提取type=中的内容,open和close标记之间没有任何内容。怎么做?在


Tags: pydownloadstypelineopentestingusersfile
2条回答

根据您的编辑(以及原始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

换言之,我认为你想要这样的东西:

^{pr2}$

请参阅文档here。在

移除

f.close()

排队!当使用with open()语法时,它会自动完成,而且名称f只在with块内有效。在

相关问题 更多 >

    热门问题