簡體   English   中英

“ 01”字符串表示在python 2中將字節轉換為unicode

[英]“01”-string representing bytes to unicode conversion in python 2

如果我有字節1100101001001010 ,如果它是有效的代碼點,如何將其轉換回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')

通過將整數值放入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 byte

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM