从文件解析xml时出错,但不是字符串?Python

2024-06-16 12:22:27 发布

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

我试图使用xml2dict来解析大量的xml文件,以便将它们转换为数据帧,但是,当我尝试解析实际的xml文件时,我得到了一个错误:

"ExpatError: not well-formed (invalid token): line 1, column 5"

这个错误对于所有的xml文件都是一样的,包括“第1行,第5列”,它们的长度相差很大,但结构都是相同的。在

当我试图将xml文件的内容复制为python中的字符串时,xml2dict的解析工作非常完美。例如:

^{pr2}$

在上面的例子中,nestdict1抛出错误,nestdict2没有问题,尽管xmlstr是来自文件'Train/DrugBank/Aciclovir_ddi.xml'的直接复制和粘贴


Tags: 文件数据token内容错误linenotcolumn
1条回答
网友
1楼 · 发布于 2024-06-16 12:22:27

您需要传递一个file对象,而不是一个作为文件名的字符串。在

docs

In [4]:print(xmltodict.parse.__doc__)
Parse the given XML input and convert it into a dictionary.

    `xml_input` can either be a `string` or a file-like object.

因此,创建一个文件描述符,如下所示:

^{pr2}$

然后将其传递给parse方法:

x2d.parse(fd)

相关问题 更多 >