python-3.x - python - 情感分析接收错误:'int'对象不可迭代

我在csv文件上运行情感分析,并且收到这个错误消息,

这是我的代码:


def sentimentAFINN(text):


 words = pattern_split.split(text.lower())


 sentiments = len(list(map(lambda word: afinn.get(word, 0), words)))


 if sentiments:


 sentiment = float(sum(sentiments))/math.sqrt(len(sentiments))



 else:


 sentiment = 0


 return sentiment



def sentimentDisplayValue(sentimentScore):


 if sentimentScore > 0.1:


 return"Positive" 


 elif sentimentScore < -0.1:


 return"Negative"


 else:


 return"Neutral"



totals = defaultdict(int)



for (index, row) in data.iterrows():


 text = row['comment']


 text_munged = munger(text)


 sentimentScore = sentimentAFINN(text_munged)


 sentimentDisplay = sentimentDisplayValue(sentimentScore)


 totals[sentimentDisplay] = totals[sentimentDisplay] + 1


 pt.add_row([text_munged, sentimentScore, sentimentDisplay])



print (pt)


print (totals)



这是错误消息:


TypeError Traceback (most recent call last)


<ipython-input-73-b20887003b41> in <module>


 4 text = row['LikelyToReferComment']


 5 text_munged = munger(text)


----> 6 sentimentScore = sentimentAFINN(text_munged)


 7 sentimentDisplay = sentimentDisplayValue(sentimentScore)


 8 totals[sentimentDisplay] = totals[sentimentDisplay] + 1



<ipython-input-72-f95f79f94b60> in sentimentAFINN(text)


 29 sentiments = len(list(map(lambda word: afinn.get(word, 0), words)))


 30 if sentiments:


---> 31 sentiment = float(sum(sentiments))/math.sqrt(len(sentiments))


 32 


 33 else:



TypeError: 'int' object is not iterable



时间:

你的sentiments变量是一个int,因为它的值由len()返回,试图在sum()len()上调用sentimentssum()len()都需要一个iterable数据类型。

你可以像这样改变你的sentimentAFINN()


def sentimentAFINN(text):


 words = pattern_split.split(text.lower())


 # save your list in sentiments


 sentiments = list(map(lambda word: afinn.get(word, 0), words))


 # now you check length of sentiments and return accordingly


 return float(sum(sentiments))/math.sqrt(len(sentiments)) if len(sentiments) > 0 else 0



...