Python html 字母表

标签 python python-3.x

有没有更简单的方法将非 html 字母转换为 html 字母?例如,如果我执行 function("a") ,它将返回 "a" 我知道如何执行此操作的唯一方法是:

 def function(text):
      return text.replace('a','a')

那么有没有更好的方法来做到这一点,或者使用替换是实现这一目标的唯一方法?

最佳答案

使用html.entities.codepoint2namere.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>')
'&lt;&#97;&gt;'

关于Python html 字母表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18820436/

相关文章:

python - 在 Python 中使用正则表达式更改文件中的部分字符串

python - 如何在python中将字符串转换为没有时间的日期

python - 如何在 python Requests 库中使用基本的 HTTP 身份验证?

python - 如何从 QWebEngineView 禁用 contextMenu?

python - 将多个参数传递给一个函数?

python - Matplotlib:向 cartopy 图像添加颜色条

python-3.x - 如何在Python中将变量的值放在句子的中间?

python - 如何在 python 中将对象作为命令行参数传递?

python - 重载类变量(属性)的Pythonic方法是什么?

python - Python中的Powerset算法: difference between + and append on lists