[英]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()
函數 ,然后格式化結果整數,可以輕松獲得該值:
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))
該函數返回一個元組而不是一個列表。 大概這根本不需要是可變的。 您可能要考慮使用namedtuple
類,以便也可以使用屬性訪問。
演示:
>>> def codepoints(c):
... codepoint = ord(c)
... return ('U+{:04X}'.format(codepoint), '&#{:d};'.format(codepoint))
...
>>> codepoints('@')
('U+0040', '@')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.