【发布时间】:2010-10-30 04:57:45
【问题描述】:
Python 中是否有与 PHP 函数 htmlspecialchars() 类似或等效的函数?到目前为止我发现的最接近的是 htmlentitydefs.entitydefs()。
【问题讨论】:
-
似乎有不止一种明显的方法可以做到这一点!哦不!
标签: php python html-entities htmlspecialchars
Python 中是否有与 PHP 函数 htmlspecialchars() 类似或等效的函数?到目前为止我发现的最接近的是 htmlentitydefs.entitydefs()。
【问题讨论】:
标签: php python html-entities htmlspecialchars
只需要转义五个字符,所以可以使用简单的一行函数:
def htmlspecialchars(content):
return content.replace("&", "&").replace('"', """).replace("'", "'").replace("<", "<").replace(">", ">")
【讨论】:
在@garlon4 答案的基础上,您可以定义自己的htmlspecialchars(s):
def htmlspecialchars(text):
return (
text.replace("&", "&").
replace('"', """).
replace("<", "<").
replace(">", ">")
)
【讨论】:
我认为最简单的方法就是使用替换:
text.replace("&", "&").replace('"', """).replace("<", "<").replace(">", ">")
PHP 只使用 htmlspecialchars 转义这四个实体。请注意,如果您在 PHP 中设置了 ENT_QUOTES,则需要将引号替换为 '而不是“。”
【讨论】:
from django.utils.html import escape
print escape('<div class="q">Q & A</div>')
【讨论】:
html.entities 模块(htmlentitydefs 用于 python 2.x)包含一个字典 codepoint2name,它应该可以满足您的需要。
>>> import html.entities
>>> html.entities.codepoint2name[ord("&")]
'amp'
>>> html.entities.codepoint2name[ord('"')]
'quot'
【讨论】:
你可能想要xml.sax.saxutils.escape:
from xml.sax.saxutils import escape
escape(unsafe, {'"':'"'}) # ENT_COMPAT
escape(unsafe, {'"':'"', '\'':'''}) # ENT_QUOTES
escape(unsafe) # ENT_NOQUOTES
看看xml.sax.saxutils.quoteattr,它可能对你更有用
【讨论】:
我知道的最接近的是cgi.escape。
【讨论】:
如果您使用的是 django 1.0,那么您的模板变量将已经被编码并准备好显示。如果您不希望全局开启,也可以使用 safe 运算符 {{ var|safe }}。
【讨论】: