Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.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 XML文档可以';由于字符奇怪,无法进行分析_Python_Xml Parsing - Fatal编程技术网

Python XML文档可以';由于字符奇怪,无法进行分析

Python XML文档可以';由于字符奇怪,无法进行分析,python,xml-parsing,Python,Xml Parsing,我使用Python3从API中检索数据,但从检索到的字符串解析一些XML文档时遇到问题 我已确定导致此问题的特定字符串: 从xml.etree导入元素树 坏字符串='Sample‘;cp 99-3a和#x92' ElementTree.fromstring(坏字符串) 这是停止脚本的返回错误: ParseError:格式不正确(无效令牌):第1行第31列 我尝试使用一些解决方案来解决这个问题,比如下面的解决方案,结果与之前相同 ElementTree.fromstring('Samp

我使用Python3从API中检索数据,但从检索到的字符串解析一些XML文档时遇到问题

我已确定导致此问题的特定字符串:

从xml.etree导入元素树
坏字符串='Sample‘;cp 99-3a和#x92'
ElementTree.fromstring(坏字符串)
这是停止脚本的返回错误:

ParseError:格式不正确(无效令牌):第1行第31列
我尝试使用一些解决方案来解决这个问题,比如下面的解决方案,结果与之前相同

ElementTree.fromstring('Sample‘;cp 99-3a’'。encode('ascii',ignore'))
如何在不将一个特定正则表达式应用于其他类似字符串的情况下清除此字符串

编辑:既然@b_c和@mzjn解释了我的问题是未替换的字符,我找到了一个可能的解决方案()

ElementTree.fromstring('&;Sample‘;cp 99-3a’',parser=etree.XMLParser(recover=True))

您的字符串包含HTML实体(无论是XML还是HTML),需要取消转义。
分别与
'
'
相关

如果选择,您将看到已清理的文本:

>>> import html
>>> html.unescape('<tag>Sample &#x91;cp 99-3a&#x92</tag>')
'<tag>Sample ‘cp 99-3a’</tag>'
您还可以尝试使用from
lxml.html
,这在处理有问题的html/XML方面会更好:

>>> from lxml.html import soupparser
>>> soupparser.fromstring('<tag>&amp;Sample &#x91;cp 99-3 a&#x92;</tag>').text_content()
'&Sample ‘cp 99-3 a’'
>从lxml.html导入soupparser
>>>soupparser.fromstring('&;Sample‘;cp 99-3 a’;')。text_content()
'样本'cp 99-3 a'
或者,根据您的需要,您最好在解析字符串/正则表达式之前进行替换,以删除恼人的cp1252字符:

>>> import re
# Matches "&#x91" or "&#x92", with or without trailing semicolon
>>> node = ET.fromstring(re.sub(r'&#x9[1-2];?', "'", '<tag>&amp;Sample &#x91;cp 99-3 a&#x92;</tag>'))
>>> node.text
"&Sample 'cp 99-3 a'"
>>重新导入
#匹配带或不带尾随分号的“‘”或“’”
>>>node=ET.fromstring(re.sub(r'	[1-2];?',“'”,'和样本‘;cp 99-3 a’;'))
>>>node.text
“&示例‘cp 99-3 a’”

分号是不相关的,至少对于
html.unescape
来说是这样。是的,他们认为说“这是带有HTML实体的HTML”是错误的<问题中的code>坏字符串如果在
和#x92
后加上分号,则是格式良好的XML。非常感谢@b#c和@mzjn,这两种解决方案都是有效的,但现在我对
还有另一个问题。例如,当我运行
ElementTree.fromstring(html.unescape('&;Sample‘;cp 99-3a’'))
时,我遇到了与以前相同的问题。基于此更新了一些附加选项:)太棒了!这是我一直在寻找的解决方案,谢谢<代码>’
是问题所在。如果它的结尾有一个分号(
’;
),它将是一个正确的数字字符引用。看见
>>> from lxml.html import soupparser
>>> soupparser.fromstring('<tag>&amp;Sample &#x91;cp 99-3 a&#x92;</tag>').text_content()
'&Sample ‘cp 99-3 a’'
>>> import re
# Matches "&#x91" or "&#x92", with or without trailing semicolon
>>> node = ET.fromstring(re.sub(r'&#x9[1-2];?', "'", '<tag>&amp;Sample &#x91;cp 99-3 a&#x92;</tag>'))
>>> node.text
"&Sample 'cp 99-3 a'"