繁体   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