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。任何想法我如何解決這個問題?