有没有更简单的方法将非 html 字母转换为 html 字母?例如,如果我执行 function("a")
,它将返回 "a"
我知道如何执行此操作的唯一方法是:
def function(text):
return text.replace('a','a')
那么有没有更好的方法来做到这一点,或者使用替换是实现这一目标的唯一方法?
最佳答案
使用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>'
关于Python html 字母表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18820436/