簡體   English   中英

如何將特殊字符轉換為html實體?

[英]How to convert special characters into html entities?

我想在python中轉換特殊字符,如"%$!&@á é ©" ,而不僅僅是'<&">'因為我到目前為止所有的文檔和參考文獻都顯示出來.cgi.escape不會解決這個問題。

例如,字符串"á ê ĩ &"應轉換為"&aacute; &ecirc; &itilde; &amp;"

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

您可以使用http://docs.python.org/library/htmllib.html#module-htmlentitydefs中的詞典構建自己的循環。

您正在尋找的是htmlentitydefs.codepoint2name

我找到了一個內置的解決方案來搜索@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

謝謝大家的幫助! ;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM