Python 类型错误:不能pickle 生成器对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28963354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: can't pickle generator objects
提问by nlper
I am trying to write some result on to pickle file as below:
我正在尝试将一些结果写入泡菜文件,如下所示:
raw_X = (self.token_ques(text) for text in training_data)
with open('/root/Desktop/classifier_result.pkl', 'wb') as handle:
pickle.dump(raw_X, handle)
Error:
错误:
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle generator objects
Any help would be much appreciable.
任何帮助将是非常可观的。
回答by Martijn Pieters
Don't use a generator expression when you want to pickle data. Use a list comprehension instead, or call list()
on the generator to capture all generated elements for pickling.
当您想要腌制数据时,不要使用生成器表达式。改用列表理解,或调用list()
生成器来捕获所有生成的元素以进行酸洗。
For example, the following works just fine:
例如,以下工作正常:
raw_X = [self.token_ques(text) for text in training_data]
with open('/root/Desktop/classifier_result.pkl', 'wb') as handle:
pickle.dump(raw_X, handle)
as does:
就像:
raw_X = (self.token_ques(text) for text in training_data)
with open('/root/Desktop/classifier_result.pkl', 'wb') as handle:
pickle.dump(list(raw_X), handle)
回答by ForceBru
raw_X = (self.token_ques(text) for text in training_data)
This is a generator. As the error says, we cannot pickle generators. Use this instead.
这是一个发电机。正如错误所说,我们不能pickle 生成器。改用这个。
raw_X=[]
for text in data:
raw_X.append(self.token_ques(text))
raw_X=tuple(raw_X)
And pickle raw_X
then.
然后腌制raw_X
。
Edit
编辑
This works for me
这对我有用
import pickle
raw_X=[]
data=[1,2,3,4,5,6,2,0]
for text in data:
raw_X.append(str(text))
print pickle.dumps(raw_X)
I'm using str()
instead of your function and dumps()
instead of dump()
.
我正在使用str()
而不是你的函数而dumps()
不是dump()
.