3

我有一个看起来像这样的 XML 文件。相关位是这样的:

<reference>
  <citation>Vander Wal JS, Gang CH, Griffing GT, Gadde KM. Escitalopram for treatment of night eating syndrome: a 12-week, randomized, placebo-controlled trial. J Clin Psychopharmacol. 2012 Jun;32(3):341-5. doi: 10.1097/JCP.0b013e318254239b.</citation>
  <PMID>22544016</PMID>
</reference>

我试图找到该PMID字段的值,使用 PyQuery 来解析 XML:

    from pyquery import PyQuery as pq

    text = open(f, 'r').read()
    d = pq(text)
    data = {}       
    data['nct_id'] = d('nct_id').text()

    print d('reference')
    reference = d('reference')
    print reference('PMID')
    data['pmid'] = reference('PMID').text()

    print data['PMID']

为什么这不起作用?在控制台中,我看到了reference第一个打印语句的全部内容,后跟两个空值:

<reference>
    <citation>Vander Wal JS, Gang CH, Griffing GT, Gadde KM. Escitalopram for treatment of night eating syndrome: a 12-week, randomized, placebo-controlled trial. J Clin Psychopharmacol. 2012 Jun;32(3):341-5. doi: 10.1097/JCP.0b013e318254239b.</citation>
    <PMID>22544016</PMID>
  </reference>

如示例代码所示,我可以nct_id很好地使用找到文档中的其他叶节点(如)。.find()

PyQuery 不喜欢大写标签吗?

4

1 回答 1

3

您可以指定要使用的解析器,它将起作用:

d = pq(text, parser='xml')
于 2016-08-24T16:56:51.423 回答