【问题标题】:Convert string from xmlcharrefreplace back to utf-8将字符串从 xmlcharrefreplace 转换回 utf-8
【发布时间】:2013-06-24 20:42:53
【问题描述】:

我有下一部分代码:

In [8]: st = u"опа"

In [11]: st.encode("ascii", "xmlcharrefreplace")
Out[11]: 'опа'

In [14]: st1 = st.encode("ascii", "xmlcharrefreplace")

In [15]: st1.decode("ascii", "xmlcharrefreplace")
Out[15]: u'опа'

In [16]: st1.decode("utf-8", "xmlcharrefreplace")
Out[16]: u'опа'

你知道如何将st1 转换回u"опа" 吗?

【问题讨论】:

    标签: python utf-8 encode unicode-string


    【解决方案1】:

    使用html.unescape() function(Python 3.4 及更高版本):

    >>> import html
    >>> html.unescape('опа')
    'опа'
    

    在旧版本(包括 Python 2)上,您必须使用 HTMLParser.HTMLParser() 的实例:

    >>> from HTMLParser import HTMLParser
    >>> parser = HTMLParser()
    >>> parser.unescape('опа')
    u'\u043e\u043f\u0430'
    >>> print parser.unescape('опа')
    опа
    

    【讨论】:

    • 这是完美的。我使用 Python 已经 10 多年了,这已经从字面上逃脱(不是双关语)我的搜索结果。
    猜你喜欢
    • 2019-03-20
    • 2013-03-02
    • 1970-01-01
    • 2015-08-06
    • 2018-09-30
    • 2012-12-05
    • 2012-02-20
    • 2015-04-29
    • 1970-01-01
    相关资源
    最近更新 更多