我试图用来xml2dict
解析大量的 xml 文件,以便我可以将它们转换为数据帧,但是,当我尝试解析实际的 xml 文件时,我得到了错误:
"ExpatError: not well-formed (invalid token): line 1, column 5"
对于所有 xml 文件,此错误完全相同,包括“第 1 行,第 5 列”,它们的长度差异很大,但结构都相同。
当我尝试将 xml 文件的内容复制为 python 中的字符串时,使用 xml2dict 的解析工作完美。例如:
xmlstr ="""<?xml version="1.0" encoding="utf-8"?>
<document id="DDI-DrugBank.d200">
<sentence id="DDI-DrugBank.d200.s0" text="Co-administration of probenecid with acyclovir has been shown to increase the mean half-life and the area under the concentration-time curve.">
<entity id="DDI-DrugBank.d200.s0.e0" charOffset="21-30"
type="drug" text="probenecid"/>
<entity id="DDI-DrugBank.d200.s0.e1" charOffset="37-45"
type="drug" text="acyclovir"/>
<pair id="DDI-DrugBank.d200.s0.p0" e1="DDI-DrugBank.d200.s0.e0"
e2="DDI-DrugBank.d200.s0.e1" ddi="true" type="mechanism"/>
</sentence>
<sentence id="DDI-DrugBank.d200.s1" text="Urinary excretion and renal clearance were correspondingly reduced."/>
<sentence id="DDI-DrugBank.d200.s2" text="The clinical effects of this combination have not been studied."/>
</document>"""
import xmltodict as x2d
nestdict1 = x2d.parse('Train/DrugBank/Aciclovir_ddi.xml')
nestdict2 = x2d.parse(xmlstr)
在上面的示例中,尽管是从文件中直接复制和粘贴,但在正常情况nestdict1
下会引发错误nestdict2
xmlstr
'Train/DrugBank/Aciclovir_ddi.xml'