如果沒有其他文字,分割字符串在空白處,將每個轉換爲整數並將結果提供給bytearray()
object進行解碼:
as_binary = bytearray(int(b, 2) for b in inputtext.split())
as_unicode = as_binary.decode('utf8')
通過將整數值放入bytearray()
,我們避免了連接單個字符並獲得方便的.decode()
方法作爲獎勵。
請注意,這確實希望輸入包含有效的UTF-8的。您可以添加錯誤處理程序來替換錯誤的字節,而不是引發異常,例如。
癡迷的,需要一個編解碼器和錯誤處理功能:
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 byte
你有一個實際的字節或者你有與零和的一個字符串,可以被解碼爲一個二進制值?或者你有使用'0b..'表示法的整數字面值? –
另外,UTF-8是一個多字節編解碼器,一個單字節可能是一個ASCII碼點或一個不完整的序列。你有更多的字節嗎? –
輸入是一個有0和1的字符串。 – nirvair