我正在尝试对电影评论进行情绪分析。
以下代码在函数内:
classifier = nltk.classify.SklearnClassifier(LinearSVC())
classifier.train(train_set)
如何在以后使用时保存并加载它?我应该在哪里把pickle函数放在我的代码中?感谢您的时间!
在运行pickle
后保存和读取文档时,可以使用nltk
。首先,您需要导入模块。
import pickle
classifier = nltk.classify.SklearnClassifier(LinearSVC())
classifier = classifier.train(train_set)
保存:
with open("filename", "wb") as infile:
pickle.dump(classifier, infile)
阅读:
with open("filename","rb") as outfile:
docs = pickle.load(outfile)
你可以使用pickle
。
写作:
import pickle as pkl
clf = nltk.classify.SklearnClassifier(LinearSVC())
clf.train(X_train,y_train)
with open('clf.pkl','wb') as myfile:
pkl.dump(clf,myfile)
阅读:
import pickle as pkl
with open('clf.pkl','wb') as myfile:
clf = pkl.load(myfile)
保存:
def save(name,data,type='.dat'):
name+=type
pickle.dump(data,open(name,'wb'))#will create file if doesn't exist,will update file if there is such file
加载:
def load(name):
return pickle.load(open(name,'rb'))#will raise error if no such file exists
例:
save('myFile','foo')
print(load('myfile.dat'))#remember .dat !
#will prints 'foo'
你需要首先导入泡菜然后你可以保存任何东西