簡體   English   中英

如何修復此字節對象的編碼以僅保留實際文本並刪除 Python3 中的 '\\x00\\x05*\\x00\\x00\\x0e\\x00bjbj'?

[英]How can I fix the encoding of this bytes object to only keep the actual text and remove the '\x00\x05*\x00\x00\x0e\x00bjbj' in Python3?

問題:

我正在使用一個 API,它以字節對象的形式檢索感興趣的內容。

字節對象 (myobj) 的值為:

myobj = b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1\x00\x00This is \rthe sentence \rI want to \rkeep.\r\r\x03\r\r\x04\r\r\x03\r\r\x04\x017\x00\x06'

問題:

我怎么只保留這個:“這是我想保留的句子。”

我試過的:

1:我嘗試用UTF-8解碼,但輸出與輸入相同。 我還嘗試過“ascii”、“utf-16”和“utf-8”。 如果我刪除 'ignore' 參數,我會收到一個錯誤:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte

myobj.decode('utf-8', 'ignore')

2:嘗試使用 string 中的可打印函數,該函數返回的輸出與輸入幾乎相同。

import string
mystr =str(myobj)
print( ''.join(x for x in test2 if x in mystr.printable))

3:我也嘗試使用strip()和replace來刪除部分字符串,但是,有太多不同的字符。

任何建議都會很棒。

謝謝!

你已經差不多了。 結合選項 1 和 2:

new_obj = ''.join(c for c in my_obj.decode('utf-8', 'ignore') if c.isprintable())

但是,您的new_obj將是:

'This is the sentence I want to keep.7'

那是因為,在my_obj接近尾聲時,您得到了'\\x017' 這是一個值為 0x01 后跟字符'7'的字節。

暫無
暫無

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

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