【问题标题】:How to convert special characters into html entities?如何将特殊字符转换为html实体?
【发布时间】:2012-03-08 11:27:21
【问题描述】:

我想在 python 中转换像"%$!&@á é ©" 这样的特殊字符,而不仅仅是'<&">',正如我迄今为止找到的所有文档和参考资料所示。 cgi.escape 不能解决问题。

例如,字符串"á ê ĩ &" 应转换为"á ê ĩ &"

有大佬知道怎么解决吗? 我正在使用 python 2.6。

【问题讨论】:

  • 请注意两点:(1)名称实体可能会导致问题,您可能应该使用数字实体。 (2) 为什么要使用实体?在大多数情况下,更好的解决方案是对文档进行 UTF-8 编码,以便它可以包含字母,而不是使用实体。
  • 我同意你的看法@KonradRudolph。我不喜欢使用实体,但我正在使用的系统使用,所以我别无选择。 =/
  • @Jayme 没问题,有时你别无选择。只是想确保您知道这一点。

标签: python html html-entities


【解决方案1】:

您可以使用在http://docs.python.org/library/htmllib.html#module-htmlentitydefs 中找到的词典构建自己的循环

你要找的是htmlentitydefs.codepoint2name

【讨论】:

  • 链接失效了。在 Python 2 中使用 HTMLParser,在 Python 3 中使用等效的 html.parser。
【解决方案2】:

我找到了一个内置的解决方案来搜索@Ruben Vermeersch 在他的回答中所说的 htmlentitydefs.codepoint2name。解决方案在这里找到:http://bytes.com/topic/python/answers/594350-convert-unicode-chars-html-entities

函数如下:

def htmlescape(text):
    text = (text).decode('utf-8')

    from htmlentitydefs import codepoint2name
    d = dict((unichr(code), u'&%s;' % name) for code,name in codepoint2name.iteritems() if code!=38) # exclude "&"    
    if u"&" in text:
        text = text.replace(u"&", u"&")
    for key, value in d.iteritems():
        if key in text:
            text = text.replace(key, value)
    return text

感谢大家的帮助! ;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    相关资源
    最近更新 更多