【发布时间】:2020-06-21 00:38:33
【问题描述】:
可以在 Python 中使用u'\uXXX' 模式打印表情符号的十六进制代码,例如
>>> print(u'\u231B')
⌛
但是,如果我有一个像 231B 这样的十六进制代码列表,那么仅仅“添加”字符串将不起作用:
>>> print(u'\u' + ' 231B')
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape
chr() 也失败了:
>>> chr('231B')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required (got type str)
我的问题的第一部分是给定十六进制代码,例如231A 如何获取str 类型的表情符号?
我的目标是从https://unicode.org/Public/emoji/13.0/emoji-sequences.txt 获取表情符号列表并阅读第一列的十六进制代码。
在某些情况下它的范围从231A..231B,我的问题的第二部分是给定一个十六进制代码范围,我如何遍历该范围以获得表情符号str,例如2648..2653,可以做range(2648, 2653+1),但如果六进制中有一个字符,例如1F232..1F236,无法使用range()。
感谢@amadan 的解决方案!!
TL;DR
从https://unicode.org/Public/emoji/13.0/emoji-sequences.txt 获取表情符号列表到文件中。
import requests
response = requests.get('https://unicode.org/Public/emoji/13.0/emoji-sequences.txt')
with open('emoji.txt', 'w') as fout:
for line in response.content.decode('utf8').split('\n'):
if line.strip() and not line.startswith('#'):
hexa = line.split(';')[0]
hexa = hexa.split('..')
if len(hexa) == 1:
ch = ''.join([chr(int(h, 16)) for h in hexa[0].strip().split(' ')])
print(ch, end='\n', file=fout)
else:
start, end = hexa
for ch in range(int(start, 16), int(end, 16)+1):
#ch = ''.join([chr(int(h, 16)) for h in ch.split(' ')])
print(chr(ch), end='\n', file=fout)
【问题讨论】:
标签: python unicode emoji chr ord