如何修复 Python 中的 unicode/cPickle 错误?
ids = cPickle.loads(gem.value)
loads() argument 1 must be string, not unicode
ids = cPickle.loads(gem.value)
loads() argument 1 must be string, not unicode
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
cPickle.loads
想要一个字节字符串(这正是cPickle.dumps
输出的内容),而您却向它提供了一个 unicode 字符串。您需要“编码”该 Unicode 字符串才能取回dumps
最初给您的字节字符串,但很难猜测您不小心对其强加了什么编码 - 也许是latin -1
或utf-8
(如果ascii
不担心,这两个中的任何一个都可以很好地解码它),也许utf-16
...?如果不知道gem
是什么以及您最初如何从cPickle.dumps
的输出设置其值
,就很难猜测...!cPickle.loads
wants a byte string (which is exactly whatcPickle.dumps
outputs) and you're feeding it a unicode string instead. You'll need to "encode" that Unicode string to get back the byte string thatdumps
had originally given you, but it's hard to guess what encoding you accidentally imposed on it -- maybelatin-1
orutf-8
(ifascii
don't worry, either of those two will decode it just great), maybeutf-16
...? It's hard to guess without knowing whatgem
is and how you originally set itsvalue
from the output of acPickle.dumps
...!cPickle.dumps()
的结果是一个str
对象,而不是unicode
对象。您需要在代码中找到解码 pickledstr
对象的步骤,并忽略该步骤。不要尝试将
unicode
对象转换为str
对象。两个错误并不能构成一个正确。示例(Python 2.6):您很可能正在使用默认(且效率低下)的协议 0,它会产生“人类可读”的输出:
大概是 ASCII(但没有记录如此),因此
str(gem.value)
拼凑很可能“”“工作”“”:The result of
cPickle.dumps()
is astr
object, not aunicode
object. You need to find the step in your code where you are decoding the pickledstr
object, and omit that step.DON'T try to convert your
unicode
object to astr
object. Two wrongs don't make a right. Example (Python 2.6):You may well be using the default (and inefficient) Protocol 0 which produces "human readable" output:
which is presumably ASCII (but not documented to be so) so the
str(gem.value)
kludge may well """work""":您可以通过将 gem.value 设置为字符串而不是 unicode 来修复此问题。
使用str(gem.value)
You can fix it by making
gem.value
a string, not unicode.Use
str(gem.value)