nir*_*air 0 python unicode utf-8 python-2.7
如果我有字节 - 11001010或者01001010,如果它是一个有效的代码点,如何将其转换回Unicode?
我可以接受输入并对输入进行正则表达式检查,但这将是一种粗略的方式,它将仅限于UTF-8.如果我希望将来扩展,我该如何优化解决方案?
输入是0和1的字符串 -
11001010这是无效的
或者01001010这是有效的
或者11010010 11001110这是无效的
如果没有其他文本,请在空格上拆分字符串,将每个字符串转换为整数并将结果提供给要解码的bytearray()对象:
as_binary = bytearray(int(b, 2) for b in inputtext.split())
as_unicode = as_binary.decode('utf8')
Run Code Online (Sandbox Code Playgroud)
通过将整数值放入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)
Run Code Online (Sandbox Code Playgroud)
大多数样本实际上并不是有效的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'
Run Code Online (Sandbox Code Playgroud)
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 byte
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
109 次 |
| 最近记录: |