我有这本字典定义:
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
稍后,我想使用 pickle 并将字典转储到文本文件中:
f = open('dict.txt', 'wb')
pickle.dump(Nwords, f)
但是代码不起作用,我收到一个错误。显然pickle
不能使用lambda
,我最好定义model
使用模块级函数。我已经在这里阅读了答案
不幸的是,由于我没有使用 Python 的经验,我不确定如何做到这一点。我试过了:
def dd():
return defaultdict(int)
def train(features):
## model = defaultdict(lambda: 1)
model = defaultdict(dd)
for f in features:
model[f] += 1
return model
我收到错误:
TypeError: unsupported operand type(s) for +=: 'collections.defaultdict' and 'int'
除此之外,return defaultdict(int)
总是将零分配给第一次出现的键,而我希望它分配 1。关于如何解决这个问题的任何想法?