w
Scripting all our processes in Python allowed us to efficiently and mostly automatically acquire, clean, translate, and analyse our dataset of nearly 100.000 tweets. Each step of our workflow had one dedicated script. For the sake of intersubjective reproducibility, the following page contains our code. If you are not familiar with programming, you can find explanatory texts.
There are further scripts, which were obligatory and do not embody our decisions regarding the data analysis. For this, we do not consider them as important enough for being included here. For transparency, they are published on our GitHub repository. Folders with the name "initialTests" contain scripts, which we wrote but could not use in the end. For example, we intended to employ the NRC Word-Emotion Association Lexicon (aka EmoLex). However, after implementing the script, the results were unsatisfying due to a missing overlap of terms in the EmoLex and our dataset. Lastly, on the subpage Queries you can find SPARQL scripts, which we used for querying our data.
We acquired the data by exploiting the Twitter API. The Twitter API is available as a free version and as a premium version. The premium version is available without cost for a limited amount of requests. We opt for the premium because the free version only offers the download of tweets posted within the last seven days. In the following script, we first acquired the data by using the TwitterAPI library, and then we used the Pandas library to store the tweets within a CSV file.
The script shows that we are removing retweets. We consider retweets as duplicates of information. However, we believe the times an original tweets has been retweeted strengenths its importance and, hence, we store this information adequately.
# -*- coding: utf-8 -*-
from TwitterAPI import TwitterAPI, TwitterPager
import csv
### Twitter API Credentials ###
consumer_key='###'
consumer_secret='###'
access_token_key='###'
access_token_secret='###'
### Product Selection ###
PRODUCT = '30day'
LABEL = 'EURELsandbox'
### Filepath for Storing ###
csvFile = open('download.csv', 'a')
csvWriter = csv.writer(csvFile)
csvWriter.writerow(["created_at", "lang", "screen_name", "location", "full_text", "urls", "tags", "mentions", "retweet_count", "favorite_count"])
count_tweets = 0
count_retweets = 0
api = TwitterAPI(consumer_key,consumer_secret,access_token_key,access_token_secret)
data = TwitterPager(api, 'tweets/search/%s/:%s' % (PRODUCT, LABEL),
{'query':'European Elections lang:en', 'fromDate':'201905270001', 'toDate':'201906022359'})
for tweet in data.get_iterator():
if 'retweeted_status' not in tweet:
count_tweets += 1
user = tweet['user']
list_tags = [tags['text'] for tags in tweet['entities']['hashtags']]
list_tags = ', '.join(list_tags)
list_mentions = [mentions['screen_name'] for mentions in tweet['entities']['user_mentions']]
list_mentions = ', '.join(list_mentions)
list_urls = [urls['expanded_url'] for urls in tweet['entities']['urls']]
list_urls = ', '.join(list_urls)
if 'extended_tweet' in tweet:
csvWriter.writerow([tweet['created_at'], tweet['lang'], user['screen_name'], user['location'], tweet['extended_tweet']['full_text'], list_urls, list_tags, list_mentions, tweet['retweet_count'], tweet['favorite_count']])
elif 'text' in tweet:
csvWriter.writerow([tweet['created_at'], tweet['lang'], user['screen_name'], user['location'], tweet['text'], list_urls, list_tags, list_mentions, tweet['retweet_count'], tweet['favorite_count']])
print('Yeah, found already a total of',count_tweets,'tweets!')
elif 'retweeted_status' in tweet:
count_retweets += 1
print('Ups, that adds up to',count_retweets,'useless retweets...')
The cleaning of our raw data was necessary for several reasons. For instance, we acquired the data with two systems, one running Windows 8.1 and one macOS Mojave, due to the differences the formatting was partially different. Further, we needed to separate URLs, hashtags, emojis and mentions from the text for the analysing step.
In the script, you can see how we first aligned the formate of date and time, then strip off the additional information and store them in separate columns. The library Tweet Preprocessor has helped us significantly with this task. In the last step, we further clean the data to reduce the size of the data, which we transferred to the sentiment analysis system Sentilo. The reduction was required because the communication with Sentilo employs HTTP GET requests, which have certain limitations.
# -*- coding: utf-8 -*-
import pandas as pd
import preprocessor as p
import string
import nltk
from nltk.corpus import stopwords
import re
emoji_pattern = re.compile("[" u"\U00002702-\U0001F9F0" "]+", flags=re.UNICODE)
p.set_options(p.OPT.URL, p.OPT.MENTION, p.OPT.HASHTAG)
for file in filenames:
df = pd.read_csv(file, delimiter = ";", encoding="utf-8", skiprows=1, names = ["created_at", "lang", "screen_name", "location", "full_text", "urls", "tags", "mentions", "retweet_count", "favorite_count"])
df["parsed_text"] = ""
df["emoji"] = ""
df["created_at"] = df["created_at"].map(lambda x: x.replace('+0000',''))
df["created_at"] = df["created_at"].map(lambda x: x.replace('Mon',''))
df["created_at"] = df["created_at"].map(lambda x: x.replace('Tue',''))
df["created_at"] = df["created_at"].map(lambda x: x.replace('Wed',''))
df["created_at"] = df["created_at"].map(lambda x: x.replace('Thu',''))
df["created_at"] = df["created_at"].map(lambda x: x.replace('Fri',''))
df["created_at"] = df["created_at"].map(lambda x: x.replace('Sab',''))
df["created_at"] = df["created_at"].map(lambda x: x.replace('Sun',''))
df["created_at"] = df["created_at"].map(lambda x: x.replace('2019',''))
df["created_at"] = df["created_at"].map(lambda x: x.strip())
for index, row in df.iterrows():
line = row["created_at"]
row["created_at"] = line[:7] + '2019 ' + line[7:]
tmp_parsed_text = p.clean(row["full_text"])
tmp_emoji = re.findall(emoji_pattern, tmp_parsed_text)
for emoji in tmp_emoji:
tmp_parsed_text = tmp_parsed_text.replace(emoji,"")
tmp_emoji = ", ".join(tmp_emoji)
df.at[index,"emoji"] = tmp_emoji
tmp_parsed_text= re.sub(" +", " ", tmp_parsed_text)
df.at[index,"parsed_text"] = tmp_parsed_text
print(file)
df.to_csv(file, sep = ";", index=False)
for file in filenames:
df = pd.read_csv(file, delimiter = ";", encoding="utf-8", skiprows=1, names = ['created_at', 'lang', 'screen_name', 'location', 'full_text', 'urls', 'tags', 'mentions', 'retweet_count', 'favorite_count', 'parsed_text', 'emoji', 'english'])
df["clean"] = ""
for index, row in df.iterrows():
stop_words = stopwords.words('english')
sentence = str(row["english"])
sentence = sentence.lower()
sentence = re.sub(r'\d+', '', sentence)
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
sentence = sentence.strip()
sentence = [word for word in sentence.split() if word not in stop_words]
sentence = ' '.join(sentence)
df.at[index,"clean"] = sentence
print(file)
df.to_csv(file, sep = ";", index=False)
Our first draft of Europinion already included the objective to represent the opinion and the sentiment of all EU citizens. For achieving this goal, we needed to acquire tweets in all 24 official EU languages. However, Sentilo requires the data to be in English. To analyse our data, we, hence, needed to translate strings with a total length of about 9.000.000 characters.
Most services like Google are monetising their APIs nowadays – analysing 9.000.000 characters with Google is not possible for a no-budget project ($20/one million chr.). The Russian company Yandex offers a Translate API, which is, to some extent, free. The API supports the transfer of 10.000 characters at a time. Given that an average tweet has only 90 characters, we decided to write a script which first groups tweets into packages and then transfers the data.
# -*- coding: utf-8 -*-
import pandas as pd
import requests
import time
# A key can be used for 1.000.000 chr/day and 10.0000.000 chr/month
key = '###'
# Uncomment one file at a time to avoid issues.
filenames = [ # List of all local files.
]
### Function for Saving to CSV ###
def saving(response, index):
responseJSON = response.json()
responseLIST = responseJSON["text"][0].split(" [!] ")
start = index - len(responseLIST) + 1
end = index
indices = list(range(start, end + 1))
position = 0
for tweet in indices:
df.at[tweet,"english"] = responseLIST[position]
position += 1
print("Saving... lastSuccess:", index)
df.to_csv(file, sep = ";", index=False)
### Sending Packages to Yandex ###
def sending(package, index):
text = " [!] ".join(package)
lang = "en"
data = {"key": key, "text": text, "lang": lang}
try:
response = requests.post("https://translate.yandex.net/api/v1.5/tr.json/translate", data=data)
saving(response, index)
except requests.exceptions.RequestException as e:
print(e)
print("Waiting for 60 sec.")
time.sleep(60)
sending(package, index)
### Packaging Tweets with the Seperator " [!] " ###
def packaging(lastSuccess = -1):
package = []
packageCount = 0
for index, row in df.iterrows():
if sum(len(tweets) for tweets in package) < 8500 and index > lastSuccess:
package.append(row["parsed_text"])
if sum(len(tweets) for tweets in package) >= 8500 and len(df.index) - 1 != index:
packageCount += 1
print("Sending... Package nr.", packageCount, "– Progress:", round((index / (len(df.index) - 1)) * 100, 2), "%")
sending(package, index)
package = []
time.sleep(5)
elif len(df.index) - 1 == index:
packageCount += 1
print("Sending LAST package for", file, "– Progress:", round((index / (len(df.index) - 1)) * 100, 2), "%")
sending(package, index)
time.sleep(5)
### Triggering the Chain of Functions ###
for file in filenames:
### Two types of files:
### NEW FILE – NOT opened before -> has no "english" column
df = pd.read_csv(file, delimiter = ";", encoding="utf-8", skiprows=1, names = ["created_at", "lang", "screen_name", "location", "full_text", "urls", "tags", "mentions", "retweet_count", "favorite_count", "parsed_text", "emoji"])
df["english"] = ""
df.to_csv(file, sep = ";", index=False)
### OLD FILE – partially translated
df = pd.read_csv(file, delimiter = ";", encoding="utf-8", skiprows=1, names = ["created_at", "lang", "screen_name", "location", "full_text", "urls", "tags", "mentions", "retweet_count", "favorite_count", "parsed_text", "emoji", "english"])
### NEW FILE – leave brackets blank: packaging()
packaging()
### OLD FILE – input is lastSuccess: packaging(lastSuccess)
packaging(lastSuccess)
Generally, we used Sentilo for the sentiment analysis. Sentilo returns a sentiment network for each tweet, from which we then extracted the sentiment values. The analysis with Sentilo delivered us the data for our ultimate opinion and sentiment mining. The analysing step also included the restructuring of our data. We used the sentiment scores and our CSV files to populate our Knowledge Graph. The flexible structure of a graph enables us to further enrich the data with future additions, like the Sentiment and Emotion Lexicons by Saif M. Mohammad.
The following script transmits the data to Sentilo. The code is written in such a way that there are no more than five HTTP requests open between the client and the server at the same time. In this way, we intended to avoid overloading the server. We used the library RDFLib to add the data as triples (subject, predicate and object) to our named graph. The resulting file is an RDF/XML.
# -*- coding: utf-8 -*-
import statistics
import json
import time
import requests
import rdflib
import re
import pandas as pd
from rdflib import *
from threading import Thread
from nested_lookup import nested_lookup
filenames = [ # List of all local files.
]
langDict = { # List of all language abbreviations.
}
sleep = 0
tries = list()
def initiate(langID):
global eur, eurGraph, election
eur = Namespace('http://www.europinion.com/')
eurGraph = Graph()
eurGraph.bind('eur', eur, override=False)
election = URIRef('http://www.europinion.com/2019/')
lang = URIRef('http://www.europinion.com/2019/' + langID + '/')
eurGraph.add((election, eur.lang, lang))
def adding(index, row, responseDict, langID):
global count
tweetID = URIRef('http://www.europinion.com/2019/' + langID + '/' + str(count))
langForTweet = URIRef('http://www.europinion.com/2019/' + langID + '/')
eurGraph.add((langForTweet, eur.hasTweet, tweetID))
eurGraph.add((tweetID, eur.createdBy, Literal(row['screen_name'])))
eurGraph.add((tweetID, eur.hasText, Literal(row['full_text'])))
eurGraph.add((tweetID, eur.hasParsed, Literal(row['parsed_text'])))
eurGraph.add((tweetID, eur.hasTranslation, Literal(row['english'])))
eurGraph.add((tweetID, eur.hasLang, Literal(row['lang'])))
### Retweets
if row['retweet_count'] != 0:
eurGraph.add((tweetID, eur.hasRetweet, Literal(int(row['retweet_count']))))
### Favourite
if row['favorite_count'] != 0:
eurGraph.add((tweetID, eur.isFavorite, Literal(int(row['favorite_count']))))
### Location
if pd.isnull(row['location']) == False:
eurGraph.add((tweetID, eur.hasLocation, Literal(row['location'])))
eurGraph.add((tweetID, eur.hasDate, Literal(row['created_at'],datatype=XSD.date)))
timestamp = re.findall('(\d\d:\d\d:\d\d)', row['created_at'])[0]
eurGraph.add((tweetID, eur.hasTime, Literal(timestamp, datatype=XSD.time)))
### Emoji
if pd.isnull(row['emoji']) == False:
emojiList = row['emoji'].split(',')
for item in emojiList:
tmp = item.strip()
eurGraph.add((tweetID, eur.hasEmoji, Literal(item)))
### Mentions
if pd.isnull(row['mentions']) == False:
mentionsList = row['mentions'].split(',')
for item in mentionsList:
tmp = item.replace(" ", "")
eurGraph.add((tweetID, eur.hasMention, Literal(tmp)))
### URLs
if pd.isnull(row['urls']) == False:
urlsList = row['urls'].split(',')
for item in urlsList:
tmp = item.strip()
eurGraph.add((tweetID, eur.hasURL, Literal(tmp)))
### Hashtags
if pd.isnull(row['tags']) == False:
tagsList = row['tags'].split(',')
for item in tagsList:
tmp = item.strip()
eurGraph.add((tweetID, eur.hasHashtag, Literal(tmp)))
### Processing Positive Scores
posScoreList = nested_lookup('http://ontologydesignpatterns.org/ont/sentilo.owl#hasPosScore', responseDict)
for item in posScoreList:
eurGraph.add((tweetID, eur.hasPositiveScore, Literal(float(item[0]['value']))))
posList = [float(item[0]['value']) for item in posScoreList]
if len(posList) > 0:
eurGraph.add((tweetID, eur.hasAvgPositive, Literal(statistics.mean(posList))))
### Processing Positive Scores
negScoreList = nested_lookup('http://ontologydesignpatterns.org/ont/sentilo.owl#hasNegScore', responseDict)
for item in negScoreList:
eurGraph.add((tweetID, eur.hasNegativeScore, Literal(float(item[0]['value']))))
negList = [float(item[0]['value']) for item in negScoreList]
if len(negList) > 0:
eurGraph.add((tweetID, eur.hasAvgNegative, Literal(statistics.mean(negList))))
if ((count%10) == 0) or (index == (len(df.index) - 1)):
eurGraph.serialize(destination='output.xml', format='xml')
print(langID, 'lastSuccess:', index)
print(langID, 'lastSaved:', count)
print(langID, 'Error rate:', ((index-count)/index)*100)
def sending(index, row, langID):
global count, failure, sleep, lastIndex, tries
sentence = row['clean']
format = 'application/rdf+json'
data = {'text': sentence, 'format': format}
headers = {
'Accept': 'application/rdf+json'
}
print(langID, 'Sending... Index:', index, '– Progress:', round((index / (len(df.index) - 1)) * 100, 2), '%')
try:
r = requests.get('http://wit.istc.cnr.it/stlab-tools/sentilo/service', params=data, headers=headers)
lastIndex = index
sleep -= 1
except requests.exceptions.RequestException as e:
r = 'retry'
time.sleep(30)
sending(index, row, langID)
if str(r) == '<Response [200]>':
count += 1
responseDict = json.loads(r.text)
adding(index, row, responseDict, langID)
elif str(r) == 'retry':
pass
else:
print(langID, r)
failure = failure.append(row, ignore_index=False)
failure.to_csv('Data/sentilo-failure.csv', sep = ";", index=False)
print(langID, 'Failed:', sentence)
def iterating(lastSuccess=-1, lastSaved=-1, langID=None):
global count, sleep
threads = []
count = lastSaved + 1
for index, row in df.iterrows():
if index > lastSuccess:
sleep += 1
t = Thread(target=sending, args=(index, row, langID,))
threads.append(t)
t.start()
time.sleep(1)
while sleep == 5:
time.sleep(0.1)
for file in filenames:
global count
global failure
langID = langDict[file]
failure = pd.read_csv('Data/sentilo-failure.csv', delimiter = ';', encoding='utf-8', skiprows=1, names = ['created_at', 'lang', 'screen_name', 'location', 'full_text', 'urls', 'tags', 'mentions', 'retweet_count', 'favorite_count', 'parsed_text', 'emoji', 'english', 'clean'])
df = pd.read_csv(file, delimiter = ';', encoding='utf-8', skiprows=1, names = ['created_at', 'lang', 'screen_name', 'location', 'full_text', 'urls', 'tags', 'mentions', 'retweet_count', 'favorite_count', 'parsed_text', 'emoji', 'english', 'clean'])
initiate(langID)
eurGraph.parse('output.xml', format='xml')
### First try: iterating()
### Consecutive try: iterating(lastSuccess, lastSaved)
iterating(1891, 770, langID=langID)