有没有更简单的方法将非html字母转换为html字母?例如,如果我执行function("a")
,它将返回"a"
,我知道如何这样做的唯一方法是:
def function(text):
return text.replace('a','a')
那么,是否有更好的方法来做到这一点,还是使用替换是实现这一目标的唯一途径?
发布于 2013-09-15 20:45:47
使用html.entities.codepoint2name
和re.sub
import html.entities
import re
def to_entitydef(match):
n = ord(match.group())
name = html.entities.codepoint2name.get(n)
if name is None:
return '&#{};'.format(n)
return '&{};'.format(name)
def escape(text):
return re.sub('.', to_entitydef, text)
示例:
>>> escape('<a>')
'<a>'
发布于 2013-09-15 20:36:04
尝试(Definitions of HTML general entities)模块。
不过,如果有人能举出一个具体的例子,那会有帮助的
https://stackoverflow.com/questions/18820436
复制相似问题