python中的捕获异常
上述函数只需取单词特征向量的平均值即可计算出特征向量。但是如果字数等于0,它会抛出一个错误,所以我使用if条件来处理这个问题。但现在,当我以以下方式调用此函数时,我面临一些问题:python中的捕获异常,python,Python,上述函数只需取单词特征向量的平均值即可计算出特征向量。但是如果字数等于0,它会抛出一个错误,所以我使用if条件来处理这个问题。但现在,当我以以下方式调用此函数时,我面临一些问题: def makeFeatureVec(words, model, num_features): # Function to average all of the word vectors in a given # paragraph # # Pre-initialize an empty
def makeFeatureVec(words, model, num_features):
# Function to average all of the word vectors in a given
# paragraph
#
# Pre-initialize an empty numpy array (for speed)
featureVec = np.zeros((num_features,),dtype="float32")
#
nwords = 0.
#
# Index2word is a list that contains the names of the words in
# the model's vocabulary. Convert it to a set, for speed
index2word_set = set(model.index2word)
#
# Loop over each word in the review and, if it is in the model's
# vocaublary, add its feature vector to the total
for word in words:
if word in index2word_set :
nwords = nwords + 1.
featureVec = np.add(featureVec,model[word])
#
# Divide the result by the number of words to get the average
if nwords == 0 :
return -1
featureVec = np.divide(featureVec,nwords)
return featureVec
以下是错误回溯:
feature = makeFeatureVec(words, model, int(num_features))
if feature != -1 :
docs_feature_vec.append(feature)
回溯(最近一次呼叫最后一次):
文件“classifier.py”,第161行,在
如果uuuu name_uuuuuu==“uuuuuuu main_uuuuuuuu”:main()
文件“classifier.py”,第159行,在main中
分类(序列文件、模型文件、标志、数量特征)
文件“classifier.py”,第144行,分类
数据,标签=创建特征向量文档(序列文件、模型文件、标志、数量特征)
文件“classifier.py”,第94行,在创建特征向量文档中
如果有功能!=-1 :
ValueError:包含多个元素的数组的真值不明确。使用a.any()或a.all()
要处理python中的错误,必须使用try
和除了
Traceback (most recent call last):
File "classifier.py", line 161, in <module>
if __name__ == "__main__": main()
File "classifier.py", line 159, in main
classify(train_file, model_file, flag, num_features)
File "classifier.py", line 144, in classify
data,label = create_feature_vector_docs(train_file, model_file, flag, num_features)
File "classifier.py", line 94, in create_feature_vector_docs
if feature != -1 :
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
不过,对于您正在做的事情,我不会推荐此解决方案
在我看来,你不应该首先返回-1而不是数组
我将返回None
,然后使用
try:
if feature != -1:
doSomething()
except Exception:
doSomethingElse()
在try
代码中,您基本上期望出现异常
这不是一个好的做法,异常只会在您不期望的情况下发生。请包含错误回溯。引发的错误是什么?如果返回无而不是-1
,则似乎您正试图根据INTI检查数组,如果功能不是None,您可以选择:
。(还有,呃,我认为这里返回None
更像python。)你问错了问题。与其弄清楚如何使用-1,不如问问自己-1是否应该首先返回。考虑<代码>!= <代码>是在返回数组时实现的。
if feature is not None:
doSomething()
else:
doSomethingElse()