Mengutip kajian yang sudah banyak dilakukan, bahwa keberadaan Twitter telah digunakan secara luas oleh berbagai lapisan masyarakat dalam beberapa tahun terakhir. Kebiasaan masyarakat mem-posting tweet untuk menilai tokoh publik atau cuitannya sendiri adalah salah satu media yang bisa dijadikan representasi tanggapan penulis atau tanggapan masyarakat terhadap tokoh publik, issue, kasus, atau sebuah produk. Saat ini memang sedang semarak, dimana ada pihak-pihak tertentu yang ingin mengetahui sentimen dan tanggapan seseorang terhadap tokoh publik atau masalah lain. Oleh karena itu, tulisan ini mudah mudahan bisa membantu menganalisis tweet berbahasa Indonesia yang sedang dibicarakan oleh pengguna twitter tersebut.
Persiapan:
pip install googletrans pip install vaderSentiment
Test Case:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer analyser = SentimentIntensityAnalyzer() analyser.polarity_scores("The movie is good")
{'neg': 0.0, 'neu': 0.508, 'pos': 0.492, 'compound': 0.4404} analyser.polarity_scores("The movie is very bad") {'neg': 0.487, 'neu': 0.513, 'pos': 0.0, 'compound': -0.5849}
Dasar Pengambilan Data dari Twitter:
import tweepy consumer_key = '<consumer key>' consumer_secret = '<consumer secret>' access_token = '<twitter akses token>' access_token_secret = '<token secret>' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth)
Terjemah ke Bahasa Indonesia
from googletrans import Translator translator = Translator() translator.translate('hola, todo bien?').text
'hello, everything okay?'
Membuat Sentimen Analisisnya:
def sentiment_analyzer_scores(text): score = analyser.polarity_scores(text) lb = score['compound'] if lb >= 0.05: return 1 elif (lb > -0.05) and (lb < 0.05): return 0 else: return -1
Script Python untuk Analisis Sentimen:
def anl_tweets(lst, title='Tweets Sentiment', engl=True ): sents = [] for tw in lst: try: st = sentiment_analyzer_scores(tw, engl) sents.append(st) except: sents.append(0) ax = sns.distplot( sents, kde=False, bins=3) ax.set(xlabel='Negative Neutral Positive', ylabel='#Tweets', title="Tweets of @"+title) return sents

Membuat Word Cloud:
import tweepy from textblob import TextBlob from wordcloud import WordCloud import pandas as pd import numpy as np import re import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') posts = api.user_timeline(screen_name="adearmando1", count = 100, lang ="in", tweet_mode="extended") # Create dataframe dengan kolomnya df = pd.DataFrame([tweet.full_text for tweet in posts], columns=['text']) # Show 5 rows data teratas df.head() # Create a function to clean the tweets def cleanTxt(text): text = re.sub('@[A-Za-z0–9]+', '', text) #Removing @mentions text = re.sub('#', '', text) # Removing '#' hash tag text = re.sub('RT[\s]+', '', text) # Removing RT text = re.sub('https?:\/\/\S+', '', text) # Removing hyperlink return text # Clean tweets df['text'] = df['text'].apply(cleanTxt) # Show cleaned tweets df def anl_tweets(lst, title='Tweets Sentiment', engl=True ): sents = [] for tw in lst: try: st = sentiment_analyzer_scores(tw, engl) sents.append(st) except: sents.append(0) ax = sns.distplot( sents, kde=False, bins=3) ax.set(xlabel='Negative Neutral Positive', ylabel='#Tweets', title="Tweets of @"+title) return sents # Create a function to get the subjectivity def getSubjectivity(text): return TextBlob(text).sentiment.subjectivity # Create a function to get the polarity def getPolarity(text): return TextBlob(text).sentiment.polarity # Create two new columns 'Subjectivity' & 'Polarity' df['Subjectivity'] = df['text'].apply(getSubjectivity) df['Polarity'] = df['text'].apply(getPolarity) # Show new dataframe 'Subjectivity' & 'Polarity' df # word cloud visualization allWords = ' '.join([twts for twts in df['text']]) wordCloud = WordCloud(width=1600, height=800, background_color='white', colormap='jet', random_state=21, max_words=50, max_font_size=200).generate(allWords) plt.figure(figsize=(12, 10)) plt.axis('off') plt.imshow(wordCloud, interpolation="bilinear") plt.show()
Menampilkan Grafik:
# Plotting plt.figure(figsize=(8,6)) for i in range(0, df.shape[0]): plt.scatter(df["Polarity"][i], df["Subjectivity"][i], color='Blue') # plt.scatter(x,y,color) plt.title('Sentiment Analysis') plt.xlabel('Polarity') plt.ylabel('Subjectivity') plt.show()
Semua informasi dan file yang saya sharing dalam website ini adalah sesuai dengan terms & comdition dari WordPress.com dan tentang keakuratan atau kebenarannya harus dilakukan cross-check, konfirmasi, termasuk dukungan agar informasi atau file yang saya sharing disini menjadi bermutu dan bermanfaat!
wah, terima kasih pak. artikelnya bagus.