如何读入Python的特殊字符

2024-06-28 15:41:14 发布

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

我正在分析一个XML文件,其中包含一些作者姓名(í = í , ï = ï , ò = ò etc)中的外语特殊字符。我的代码在尝试处理这些字符时遇到错误“ExpatError:undefined entity:”。我在网上看过beauthulsoup库,但不确定如何在不必重写lxml库的情况下轻松地将其实现到我的代码中(如果我的理解是正确的话)。解决这个问题的最好办法是什么?干杯!在

要加载的XML数据

<pub>
    <ID>75</ID>
    <title>Use of Lexicon Density in Evaluating Word Recognizers</title>
    <year>2000</year>
    <booktitle>Multiple Classifier Systems</booktitle>
    <pages>310-319</pages>
    <authors>
        <author>Petr Slav&iacute;k</author>
        <author>Venu Govindaraju</author>
    </authors>
</pub>

Python代码

^{pr2}$

Tags: 文件代码idtitleetcxmlpagesyear
2条回答

如果您使用的是python3.x,只需导入html,您可以先对提取的数据进行解码

在html.unescape(秒)

将字符串s中的所有命名和数字字符引用(例如,>;、>;、&x3e;)转换为相应的unicode字符。在

>>import html
>>print(html.unescape("Petr Slav&iacute;k"))

Petr Slavík

Seems the html-safe character cannot be parsed and returned as Document object by minidom, you have to read the file and decode it, then send as a string to the module, as the following code.

在xml.dom.minidom.parseString(字符串[,解析器])

返回表示字符串的文档。在

^{pr2}$
.encode('UTF-8') #Add to your code at the end of the example

UTF-8支持以下大多数字符:, 应该有用, 添加:

^{pr2}$

相关问题 更多 >