如何将特殊字符转换为html实体?

Jay*_*eto 5 html python html-entities

我想在python中转换特殊字符"%$!&@á é ©",而不仅仅是'<&">'我迄今为止发现的所有文档和引用.cgi.escape无法解决问题.

例如,字符串"á ê ? &"应转换为"&aacute; &ecirc; &itilde; &amp;".

anyboy是否知道如何解决它?我正在使用python 2.6.

Rub*_*sch 7

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

你正在寻找的是 htmlentitydefs.codepoint2name


Jay*_*eto 5

我找到了一个内置的解决方案来搜索@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"&amp;")
    for key, value in d.iteritems():
        if key in text:
            text = text.replace(key, value)
    return text
Run Code Online (Sandbox Code Playgroud)

谢谢大家的帮助!;)