Appendix A
The code for Twitter API credentials and extraction of tweets is below.
# Twitter API credentials
consumerKey = log[‘key’][0]
consumerSecret = log[‘key’][1]
accessToken = log[‘key’][2]
accessTokenSecret = log[‘key’][3]
bearer_token = log[‘key’][4]
accessToken
# Create the authentication object
authenticate = tweepy.OAuthHandler(consumerKey, consumerSecret)
# Set the access token and access token secret
authenticate.set_access_token(accessToken, accessTokenSecret)
# Create the API object while passing in the auth information
api = tweepy.API(authenticate, wait_on_rate_limit = True)
# Extract 2000 tweets
posts = [status for status in tweepy.Cursor(api.search, q=‘russia’, tweet_mode=‘extended’,
lang=‘uk’, retweeted= False, truncated=False).items(20)]
The code for noise removal is below.
#Create a function to clean the tweets
def cleanTxt(text):
text = re.sub(r’@[A-Za-z0-9]+’, ‘‘, text) # Removed @mentions
text = re.sub(r’#’, ‘‘, text) #Removing the “#’ symbol
text = re.sub(r’RT[\s]+’, ‘‘, text) # Removing RT
text = re.sub(r’https?:\/\/\S+’, ‘‘, text) # Remove the hyper link
text = re.sub(r’:[\s]+’, ‘‘, text) # Removing:
text = text.lstrip()
return text
#Cleaning the text
df[‘Tweets’]= df[‘Tweets’].apply(cleanTxt)
#Show the cleaned text
df
The algorithm for finding tweets with negative orientation is below.
The codes to classify subjectivity and polarity of tweets, form a word cloud, and scatterplot of subjectivity vs polarity is below.
# 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
df[‘Subjectivity’] = df[‘Tweets’].apply(getSubjectivity)
df[‘Polarity’] = df[‘Tweets’].apply(getPolarity)
#Show the new dataframe with the new columns
df
# Plot The Word Cloud
allwords = ‘ ‘.join([twts for twts in df[‘Tweets’]])
wordCloud = WordCloud(width = 1000, height=600, random_state = 21, max_font_size = 119).generate(allwords)
plt.imshow(wordCloud, interpolation = “bilinear”)
plt.axis(‘off’)
plt.show()
#Create a function to compute the negative, neutral and positive analysis
def getAnalysis(score):
if score < 0:
return ‘Negative’
elif score == 0:
return ‘Neutral’
else:
return ‘Positive’
df[‘Analysis’] = df[ ‘Polarity’ ].apply(getAnalysis)
#Show the dataframe
df
# Print all of the positive tweets
j=1
sortedDF= df.sort_values(by=[‘Polarity’])
for i in range(0, sortedDF.shape [0]):
if (sortedDF[‘Analysis’][i] == ‘Positive’):
print(str(j) + ‘) ‘+sortedDF[‘Tweets’][i])
print()
j = j+1
# Print all of the negative tweets
j=1
sortedDF= df.sort_values(by=[‘Polarity’], ascending=‘False’)
for i in range(0, sortedDF.shape[0]):
if (sortedDF[‘Analysis’][i] == ‘Negative’):
print(str(j) + ‘) ‘+sortedDF[‘Tweets’][i])
print()
j = j+1
# Plot the polarity and subjectivity
plt.figure(figsize=(8,6))
for i in range(0, df. shape[0]):
plt.scatter(df[‘Polarity’][i], df[‘Subjectivity’][i], color=‘Blue’)
plt.title(‘Sentiment Analysis’)
plt.xlabel(‘Polarity’)
plt.ylabel(‘Subjectivity’)
plt.show()
# Get the percentage of positive tweets
ptweets = df[df.Analysis== ‘Positive’]
ptweets = ptweets[‘Tweets’]
round( (ptweets.shape[0] / df.shape[0]) *100 , 1)
# Get the percentage of negative tweets
ntweets = df[df.Analysis== ‘Negative’]
ntweets = ntweets[‘Tweets’]
round( (ntweets.shape[0] / df.shape[0]) *100 , 1)
#Show the value counts
df[‘Analysis’].value_counts()
#plot and visualize the counts
plt.title(‘Sentiment Analysis’)
plt.xlabel(‘Sentiment’)
plt.ylabel (‘Counts’)
df[‘Analysis’].value_counts().plot(kind=‘bar’)
plt.show()
The code for developing Chatbot on Bot Libre platform is below.
<script type=‘text/javascript’>
SDK.applicationId = “6191571217345391239”;
var sdk = new SDKConnection();
var user = new UserConfig();
user.user = “allanmuir1”;
user.token = “1393605116044980714”;
sdk.connect(user, function() {
var web = new WebChatbotListener();
web.connection = sdk;
web.instance = “41557310”;
web.instanceName = “allantwitter bot”;
web.prefix = “botplatform”;
web.caption = “Chat Now”;
web.boxLocation = “bottom-right”;
web.color = “#009900”;
web.background = “#fff”;
web.version = 8.5;
web.bubble = true;
web.backlink = true;
web.showMenubar = true;
web.showBoxmax = true;
web.showSendImage = true;
web.showChooseLanguage = true;
web.avatar = true;
web.chatLog = true;
web.createBox();
});
</script>