Python 我该如何处理;ValueError:(';max()arg是一个空序列”;
使用上面的代码,我试图得到频率的最大值Python 我该如何处理;ValueError:(';max()arg是一个空序列”;,python,exception,Python,Exception,使用上面的代码,我试图得到频率的最大值 def build_word_affect(self): affect_list = [] affect_dict = dict() affect_frequencies = Counter() lexicon_keys = self.lexicon.keys() for word in self.words: if word in lexicon_keys: affect_l
def build_word_affect(self):
affect_list = []
affect_dict = dict()
affect_frequencies = Counter()
lexicon_keys = self.lexicon.keys()
for word in self.words:
if word in lexicon_keys:
affect_list.extend(self.lexicon[word])
affect_dict.update({word:self.lexicon[word]})
for word in affect_list:
affect_frequencies[word] += 1
sum_values = sum(affect_frequencies.values())
affect_percent = dict()
for key in affect_frequencies.keys():
affect_percent.update({key:float(affect_frequencies[key])/float(sum_values)})
self.affect_list = affect_list
self.affect_dict = affect_dict
self.raw_emotion_scores = dict(affect_frequencies)
self.affect_frequencies = affect_percent
但是出现了错误“ValueError:('max()arg是一个空序列','发生在索引36')”我发现出现错误是因为有时我输入的文本在代码中的字典键中没有任何单词-->如果字典键中的单词:
所以我尝试了一些例外,比如如果单词不在词典中
但是它不起作用…请帮我修复这个代码伙计们…提前谢谢你们
仅供参考。词典关键字中有26000个不同的单词。使用Try…除了代码
emo_dict = self.affect_frequencies
max_value = max(emo_dict.values())
我不确定我的所有内容是否与您的用法一致,因为您没有提供自给自足的代码。您需要检查
单词
的任何成员是否也在词典(keys
)中。有两种简单的方法可以做到这一点
一个是任意
函数的简单应用:
try:
if word in lexicon_keys:
affect_list.extend(self.lexicon[word])
affect_dict.update({word:self.lexicon[word]})
except ValueError as ve:
print(ve)
#code if Value error occurs
except Exception as e:
print ("NameError: str(e)")
#code if anyother error occurs
else:
#code if no errors
另一个是集合交点的简单应用:
if any(word in lexicon_keys for word in self.words):
为什么你有**用于?这是打字错误。我刚刚编辑过。你能回答这个问题以包含完整的错误回溯吗?这将更容易提供解决方案。错误是“ValueError:('max()arg是一个空序列,','发生在索引36')”
if set(self.words).intersection(set(lexicon_keys)):