我有一个如下所示的df:
text
0 Thanks, I’ll have a read!
1 Am I too late
如何将TextBlob标记化应用于句子中的每个单词,并平均每个句子中每个单词的极性得分?
例如,我可以使用一个变量中的单个句子来完成此操作:
from textblob import TextBlob
import import statistics as s
#tokenize word in sentence
a = TextBlob("""Thanks, I'll have a read!""")
print a.words
WordList(['Thanks', 'I', "'ll", 'have', 'a', 'read'])
#get polarity of every word
for i in a.words:
print( a.sentiment.polarity)
0.25
0.25
0.25
0.25
0.25
0.25
#calculating the mean of the scores
c=[]
for i in a.words:
c.append(a.sentiment.polarity)
d = s.mean(c)
print (d)
0.25
如何将a.words
应用于句子的数据帧列的每一行?
新df:
text score
0 Thanks, I’ll have a read! 0.25
1 Am I too late 0.24
我想来的壁橱是,我可以使用数据框上的此函数来获得每个句子的极性:
def sentiment_calc(text):
try:
return TextBlob(text).sentiment.polarity
except:
return None
df_sentences['sentiment'] = df_sentences['text'].apply(sentiment_calc)
先谢谢您。