Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3:无法使用xmltodict将XML转换为dict_Python_Xml_Python 3.x_Character Encoding_Xmltodict - Fatal编程技术网

Python 3:无法使用xmltodict将XML转换为dict

Python 3:无法使用xmltodict将XML转换为dict,python,xml,python-3.x,character-encoding,xmltodict,Python,Xml,Python 3.x,Character Encoding,Xmltodict,我正在尝试将数据从XML文件转换为python dict,但无法做到这一点。以下是我正在编写的代码 import xmltodict input_xml = 'data.xml' # This is the source file with open(input_xml, encoding='utf-8', errors='ignore') as _file: data = _file.read() data = xmltodict.parse(data,'ASCII')

我正在尝试将数据从XML文件转换为python dict,但无法做到这一点。以下是我正在编写的代码

import xmltodict
input_xml  = 'data.xml'  # This is the source file

with open(input_xml, encoding='utf-8', errors='ignore') as _file:
    data = _file.read()
    data = xmltodict.parse(data,'ASCII')
    print(data)
    exit()
在执行此代码时,我得到的错误如下:
xml.parsers.expat.expat错误:格式不正确(无效令牌):第239行,第40列。

经过多次尝试,我意识到我的xml在一个特定的标记中有一些印地语字符,如下所示

<DECL>!! आप की सेवा में पुनः पधारे !!</DECL>
!!आप की सेवा में पुनः पधारे !!

如何在运行
xmltodict.parse
之前忽略这些未编码字符?

我猜问题与您正在读取的文件的编码有关。 你为什么要用“ASCII”来解析它

如果您试图从python字符串中读取相同的XML,而不使用ASCII,那么它应该可以正常工作:

import xmltodict
xml = """<DECL>!! आप की सेवा में पुनः पधारे !!</DECL>"""
xmltodict.parse(xml, process_namespaces=True)
使用带有单个输入行的文件,我能够正确解析它:

import xmltodict
input_xml  = 'tmp.txt'  # This is the source file

with open(input_xml, encoding='utf-8', mode='r') as _file:
    data = _file.read()
    data = xmltodict.parse(data)
    print(data)

问题很可能是您试图将其解析为“ASCII”。

我猜问题与您正在读取的文件的编码有关。 你为什么要用“ASCII”来解析它

如果您试图从python字符串中读取相同的XML,而不使用ASCII,那么它应该可以正常工作:

import xmltodict
xml = """<DECL>!! आप की सेवा में पुनः पधारे !!</DECL>"""
xmltodict.parse(xml, process_namespaces=True)
使用带有单个输入行的文件,我能够正确解析它:

import xmltodict
input_xml  = 'tmp.txt'  # This is the source file

with open(input_xml, encoding='utf-8', mode='r') as _file:
    data = _file.read()
    data = xmltodict.parse(data)
    print(data)

问题很可能是您试图将其解析为“ASCII”。

我试图处理的文件是一个大文件,大约有2500行。如果我删除此特定标记并尝试处理它,一切正常。您是否尝试从解析方法中删除“ASCII”参数?如果没有该文件,我无法帮助您进一步了解如何向您发送该文件?您可以通过电子邮件将其发送给我。我的地址在我的个人资料上。我试图处理的文件是一个大文件,大约有2500行。如果我删除此特定标记并尝试处理它,一切正常。您是否尝试从解析方法中删除“ASCII”参数?如果没有该文件,我无法帮助您进一步了解如何向您发送该文件?您可以通过电子邮件将其发送给我。我的地址在我的个人资料上。