如果我有字节- 11001010或01001010,如果它是一个有效的代码点,如何将它转换回Unicode?
我可以接受输入,并对输入进行正则检验,但这将是一种粗略的方法,而且它将仅限于UTF-8。如果我想在未来扩展,我如何优化解决方案?
输入是带有0和1- 11001010的字符串,这是无效的。
或者01001010,这是有效的
或者11010010 11001110,这是无效的
发布于 2017-04-25 12:15:58
如果没有其他文本,则将空格上的字符串拆分,将每个字符串转换为整数,并将结果提供给 object解码:
as_binary = bytearray(int(b, 2) for b in inputtext.split())
as_unicode = as_binary.decode('utf8')通过将整数值放入bytearray()中,我们不必将单个字符连在一起,并获得一个方便的.decode()方法作为奖励。
请注意,这确实期望输入包含有效的UTF-8。您可以添加一个错误处理程序来替换错误字节,而不是引发异常,例如as_binary.decode('utf8', 'replace')。
封装为接受编解码器和错误处理程序的函数:
def to_text(inputtext, encoding='utf8', errors='strict'):
as_binary = bytearray(int(b, 2) for b in inputtext.split())
return as_binary.decode(encoding, errors)大多数示例实际上不是有效的UTF-8,因此演示程序将errors设置为'replace'。
>>> to_text('11001010', errors='replace')
u'\ufffd'
>>> to_text('01001010', errors='replace')
u'J'
>>> to_text('11001010', errors='replace')
u'\ufffd'
>>> to_text('11010010 11001110', errors='replace')
u'\ufffd\ufffd'如果要检测无效数据,请将errors保留到默认状态;只需捕获抛出的UnicodeDecodeError异常:
>>> to_text('11010010 11001110')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in to_text
File "/Users/mjpieters/Development/venvs/stackoverflow-2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd2 in position 0: invalid continuation bytehttps://stackoverflow.com/questions/43610212
复制相似问题