是否有等效于 PHP 函数 htmlspecialchars() 的 Python?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/931423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:08:22  来源:igfitidea点击:

Is there a Python equivalent to the PHP function htmlspecialchars()?

phppythonhtml-entitieshtmlspecialchars

提问by Ian

Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().

Python 中是否有与 PHP 函数 htmlspecialchars() 类似或等效的函数?到目前为止我发现的最接近的东西是 htmlentitydefs.entitydefs()。

回答by Karl Guertin

Closest thing I know about is cgi.escape.

我所知道的最接近的是cgi.escape

回答by Agonych

from django.utils.html import escape
print escape('<div class="q">Q & A</div>')

回答by Nicolas Dumazet

You probably want xml.sax.saxutils.escape:

你可能想要xml.sax.saxutils.escape

from xml.sax.saxutils import escape
escape(unsafe, {'"':'&quot;'}) # ENT_COMPAT
escape(unsafe, {'"':'&quot;', '\'':'&#039;'}) # ENT_QUOTES
escape(unsafe) # ENT_NOQUOTES

Have a look at xml.sax.saxutils.quoteattr, it might be more useful for you

看看xml.sax.saxutils.quoteattr,它可能对你更有用

回答by sykora

The html.entitiesmodule (htmlentitydefsfor python 2.x) contains a dictionary codepoint2namewhich should do what you need.

html.entities模块(htmlentitydefs用于python 2.x)包含一个字典codepoint2name,它应该可以满足您的需求。

>>> import html.entities
>>> html.entities.codepoint2name[ord("&")]
'amp'
>>> html.entities.codepoint2name[ord('"')]
'quot'

回答by garlon4

I think the simplest way is just to use replace:

我认为最简单的方法就是使用替换:

text.replace("&", "&amp;").replace('"', "&quot;").replace("<", "&lt;").replace(">", "&gt;")

PHP only escapes those four entities with htmlspecialchars. Note that if you have ENT_QUOTES set in PHP, you need to replace quotes with &#039; rather than &quot;.

PHP 仅使用 htmlspecialchars 转义这四个实体。请注意,如果您在 PHP 中设置了 ENT_QUOTES,则需要将引号替换为 ' 而不是“。

回答by AlejandroVD

Building on @garlon4 answer, you can define your own htmlspecialchars(s):

基于@garlon4 答案,您可以定义自己的htmlspecialchars(s)

def htmlspecialchars(text):
    return (
        text.replace("&", "&amp;").
        replace('"', "&quot;").
        replace("<", "&lt;").
        replace(">", "&gt;")
    )

回答by Paul Tarjan

If you are using django 1.0 then your template variables will already be encoded and ready for display. You also use the safeoperator {{ var|safe }}if you don't want it globally turned on.

如果您使用的是 django 1.0,那么您的模板变量将已经被编码并准备好显示。如果您不想全局打开它,也可以使用该 safe运算符{{ var|safe }}