如何从字符串中删除解压后遗留下来的字节串?

How do I remove bytestrings left over from decompression from a string?

我有一堆字符串,它们是看起来像这样的句子:

Having two illnesses at the same time is known as \xe2\x80\x9ccomorbidity\xe2\x80\x9d and it can make treating each disorder more difficult.

我用 .encode() 编码原始字符串,然后用 python 的 bz2 库压缩。

然后我用bz2.decompress()解压,然后用.decode()找回来。

有什么想法可以方便地从文本中删除这些字节串或避免引号等字符无法正确解码吗?

谢谢!

在我看来,您实际上没有正确解码数据,因为将 \xe2\x80\x9ccomorbidity\xe2\x80\x9d 解释为字节,解码会产生一个非常合理的字符串:

>>> b"\xe2\x80\x9ccomorbidity\xe2\x80\x9d"
b'\xe2\x80\x9ccomorbidity\xe2\x80\x9d'
>>> _.decode()
'“comorbidity”'

首先(在编码为 UTF-8 和压缩之前)该数据或原始数据未正确生成/解码,例如UTF8 数据源被读取为 ISO-8859-1(本质上是直通)。

所以这些是我要看的部分:

  • 解压后你真的正确解码了吗
  • 原始数据是否正确

我猜你错误地将上面的字节字符串“sentence”分配给了一个类型为str的对象。相反,它需要分配给一个 byte 字符串对象并将其解释为 UTF-8 字节序列。比较:

b = b'... known as \xe2\x80\x9ccomorbidity\xe2\x80\x9d and ...'
s = b.decode('utf-8')
print(b)
# b'... known as \xe2\x80\x9ccomorbidity\xe2\x80\x9d and ...'
print(s)
# ... known as “comorbidity” and ...

无论哪种方式,问题都与压缩无关:无损压缩(例如 bzip2)往返不会更改数据:

print(bz2.decompress(bz2.compress(b)).decode('utf-8'))
# ... known as “comorbidity” and ...