Python 将 unicode 字符转换为 html 代码和 unicode 数字
Python convert unicode character to html code and unicode number
这是我最终想要的:
一个字典,将 unicode 字符作为键,html 代码 + unicode 数字作为列表值。
Basic_Latin = {
...
"@": ["U+0040", "@"],
...
}
如果只给出密钥,如何实现?
我想到了这样的事情:
Basic_Latin = {
...
"@": [to_unicode(@), to_html(@)],
...
}
如果找到很多方法可以反过来转换,但不是我要找的。
符号包含的全部是字符的 Unicode 代码点的十六进制和十进制值。该值可以通过使用 ord()
function 轻松获得,然后格式化结果整数:
codepoint = ord('@')
unicode_codepoint = 'U+{:04X}'.format(codepoint) # four-digit uppercase hex
html_escape = '&#{:d};'.format(codepoint) # decimal number
或作为函数:
def codepoints(c):
codepoint = ord(c)
return ('U+{:04X}'.format(codepoint), '&#{:d};'.format(codepoint))
函数returns一个元组而不是列表;大概这毕竟不需要是可变的。您可能想考虑使用 namedtuple
class,这样您也可以使用属性访问。
演示:
>>> def codepoints(c):
... codepoint = ord(c)
... return ('U+{:04X}'.format(codepoint), '&#{:d};'.format(codepoint))
...
>>> codepoints('@')
('U+0040', '@')
这是我最终想要的:
一个字典,将 unicode 字符作为键,html 代码 + unicode 数字作为列表值。
Basic_Latin = {
...
"@": ["U+0040", "@"],
...
}
如果只给出密钥,如何实现?
我想到了这样的事情:
Basic_Latin = {
...
"@": [to_unicode(@), to_html(@)],
...
}
如果找到很多方法可以反过来转换,但不是我要找的。
符号包含的全部是字符的 Unicode 代码点的十六进制和十进制值。该值可以通过使用 ord()
function 轻松获得,然后格式化结果整数:
codepoint = ord('@')
unicode_codepoint = 'U+{:04X}'.format(codepoint) # four-digit uppercase hex
html_escape = '&#{:d};'.format(codepoint) # decimal number
或作为函数:
def codepoints(c):
codepoint = ord(c)
return ('U+{:04X}'.format(codepoint), '&#{:d};'.format(codepoint))
函数returns一个元组而不是列表;大概这毕竟不需要是可变的。您可能想考虑使用 namedtuple
class,这样您也可以使用属性访问。
演示:
>>> def codepoints(c):
... codepoint = ord(c)
... return ('U+{:04X}'.format(codepoint), '&#{:d};'.format(codepoint))
...
>>> codepoints('@')
('U+0040', '@')