这是一个初学者 OO Python 问题。我希望初学者有一个stackoverflow,如果我可以问这个而不会得到反对票。所以,我们开始吧。
当我运行此代码时:
from nltk import NaiveBayesClassifier,classify
import USSSALoader
import random
class genderPredictor():
def getFeatures(self):
if self._loadNames() != None:
maleNames,femaleNames=self._loadNames()
else:
print "There is no training file."
return
featureset = list()
for nameTuple in maleNames:
features = self._nameFeatures(nameTuple[0])
featureset.append((features,'M'))
for nameTuple in femaleNames:
features = self._nameFeatures(nameTuple[0])
featureset.append((features,'F'))
return featureset
def trainAndTest(self,trainingPercent=0.80):
featureset = self.getFeatures()
random.shuffle(featureset)
name_count = len(featureset)
cut_point=int(name_count*trainingPercent)
train_set = featureset[:cut_point]
test_set = featureset[cut_point:]
self.train(train_set)
return self.test(test_set)
def classify(self,name):
feats=self._nameFeatures(name)
return self.classifier.classify(feats)
def train(self,train_set):
self.classifier = NaiveBayesClassifier.train(train_set)
return self.classifier
def test(self,test_set):
return classify.accuracy(self.classifier,test_set)
def getMostInformativeFeatures(self,n=5):
return self.classifier.most_informative_features(n)
def _loadNames(self):
return USSSALoader.getNameList()
def _nameFeatures(self,name):
name=name.upper()
return {
'last_letter': name[-1],
'last_two' : name[-2:],
'last_is_vowel' : (name[-1] in 'AEIOUY')
}
if __name__ == "__main__":
gp = genderPredictor()
accuracy=gp.trainAndTest()
并self._loadNames()
返回None
,我得到了这个错误(来自随机导入的模块):
shuffle C:\Python27\lib\random.py 285
TypeError: object of type 'NoneType' has no len()
发生这种情况是因为尽管我在 中添加了一条return
语句,但流程跳转到了调用随机模块 ( )getFeatures(self)
的下一个类方法(即)。trainAndTest(self,trainingPercent=0.80)
random.shuffle(featureset)
所以,我想知道:如何不仅在getFeatures(self)
方法中停止过程流,而且在包含它的整个类中停止过程流?
顺便说一句,感谢Stephen Holiday分享代码。