1. 程式人生 > 實用技巧 >【520】利用 TextBlob 進行情感分析

【520】利用 TextBlob 進行情感分析

參考:Tutorial: Quickstart -TextBlob(sentimentanalysis)

參考:An overview of sentiment analysis python library: TextBlob

參考:How does TextBlob calculate sentiment polarity? How can I calculate a value for sentiment with machine learning classifier?

1.Installation of TextBlob

  Installation is not a big deal here. If you are already using CMD, you have to run this command to install TextBlob. Go to CMD and enter:

pip install textblob

  

  You need to download corpus first to train the model of TextBlob. You can achieve it using the following command:

python -m textblob.download_corpora

  

2.Steps for Sentiment Analysis Python using TextBlob

  Here is a sample code of how I used TextBlob in tweets sentiments:

from textblob import TextBlob
### My input text is a column from a dataframe that contains tweets. 

def sentiment(x):
    sentiment = TextBlob(x)
    return sentiment.sentiment.polarity

tweetsdf['sentiment'] = tweetsdf['processed_tweets'].apply(sentiment)
tweetsdf['senti'][tweetsdf['sentiment']>0] = 'positive'
tweetsdf['senti'][tweetsdf['sentiment']<0] = 'negative'
tweetsdf['senti'][tweetsdf['sentiment']==0] = 'neutral'