问题描述
我是Python的新手,但是使用PHP已有一段时间了。我正在寻找一种将所有字符([0-9A-Za-z ]
除外)转换为“ HTML小数实体”的方法。我一直在搜索,尚未找到合适的方法。我正在寻找Python中this PHP method的副本。
我找到的最接近的方法是Python中的方法,但它们不排除[0-9A-Za-z ]
:Python3 Convert all characters to HTML Entities和How can I escape *all* characters into their corresponding html entity names and numbers in Python?
就像PHP方法一样,我想要一个可以将除[0-9A-Za-z ]
之外的每个字符(当前和将来)转换为“ HTML十进制实体”并且假定使用UTF-8字符编码的函数。
例如"abcABC123 &%¤#"
将成为"abcABC123 &%¤#"
解决方法
所以我想到了这一点作为选择方法。
import re
def html_entity_encode_all(string):
return ''.join(['&#{0};'.format(ord(char)) if re.search("[^0-9A-Za-z ]",char) else char for char in string])
print(html_entity_encode_all('abcABC123 &%¤#'))
输出:abcABC123 &%¤#
但是,我不知道是否有更好的方法或更快的处理方法。