1
一本词典我有这样的字典定义:酸洗使用defaultdict
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
沿途后来,我想用咸菜和转储字典到一个文本文件:
f = open('dict.txt', 'wb')
pickle.dump(Nwords, f)
然而,代码不起作用,我收到一个错误。显然pickle
无法使用lambda
,我最好使用模块级函数定义model
。我已经阅读了答案here
不幸的是,因为我没有使用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。任何想法我如何解决这个问题?