gpt4 book ai didi

python - 在数据框中的新列中返回 TextBlob 正、负或中性分类

转载 作者:行者123 更新时间:2023-12-04 07:49:54 26 4
gpt4 key购买 nike

我正在尝试根据 TextBlob 分类插入一个仅包含“正”或“负”字符串的新数据框列:对于我的 df 的第一行,结果是 ( pos , 0.75, 0.2499999999999997)我想要' ' 在名为 'algo_sentiment' 的新列中,我一直在尝试使用以下代码:

def sentiment_algo(text):
try:
if TextBlob (text, analyzer=NaiveBayesAnalyzer()).sentiment == neg:
return 'negative'
return 'positive'
except:
return None

df_test['algo_sentiment'] = df_test['cleaned_tweets'].apply(sentiment_algo)
确实创建了新列,但总是返回所有正数或所有负数。我已经运行了一些测试,但找不到解决方案。

最佳答案

sentiment属性返回 (classification, p_pos, p_neg) 的命名元组:

>>> TextBlob('love peace', analyzer=NaiveBayesAnalyzer()).sentiment
Sentiment(classification='pos', p_pos=0.700187151810585, p_neg=0.2998128481894153)
所以把函数改成test sentiment.classification :
def sentiment_algo(text):
try:
sentiment = TextBlob(text, analyzer=NaiveBayesAnalyzer()).sentiment
return 'positive' if sentiment.classification == 'pos' else 'negative'
except:
return None
玩具示例:
df_test = pd.DataFrame({'cleaned_tweets': ['love peace', 'worst day ever']})
df_test['algo_sentiment'] = df_test['cleaned_tweets'].apply(sentiment_algo)

# cleaned_tweets algo_sentiment
# 0 love peace positive
# 1 worst day ever negative

关于python - 在数据框中的新列中返回 TextBlob 正、负或中性分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67038596/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com