-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.html
549 lines (452 loc) · 28.5 KB
/
code.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
w<!DOCTYPE html>
<html >
<head>
<!-- Site made with Mobirise Website Builder v4.10.4, https://mobirise.com -->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="generator" content="Mobirise v4.10.4, mobirise.com">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<link rel="shortcut icon" href="assets/images/eurstars-122x122.png" type="image/x-icon">
<meta name="description" content="">
<title>Code</title>
<link rel="stylesheet" href="assets/web/assets/mobirise-icons/mobirise-icons.css">
<link rel="stylesheet" href="assets/tether/tether.min.css">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap-grid.min.css">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap-reboot.min.css">
<link rel="stylesheet" href="assets/socicon/css/styles.css">
<link rel="stylesheet" href="assets/dropdown/css/style.css">
<link rel="stylesheet" href="assets/theme/css/style.css">
<link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css">
<!-- Highlight.js -->
<link rel="stylesheet" href="assets/highlightjs/highlight.css">
<script src="assets/highlightjs/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</head>
<body>
<section class="menu cid-rvgZMVDNg8" once="menu" id="menu1-g">
<nav class="navbar navbar-expand beta-menu navbar-dropdown align-items-center navbar-fixed-top navbar-toggleable-sm">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<div class="hamburger">
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</button>
<div class="menu-logo">
<div class="navbar-brand">
<span class="navbar-logo">
<a href="index.html">
<img src="assets/images/eurstars-122x122.png" alt="European Stars" title="" style="height: 3.8rem;">
</a>
</span>
<span class="navbar-caption-wrap"><a class="navbar-caption text-primary display-4" href="index.html">Europinion</a></span>
</div>
</div>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav nav-dropdown nav-right" data-app-modern-menu="true"><li class="nav-item">
<a class="nav-link link text-white display-4" href="workflow.html">Workflow</a>
</li><li class="nav-item"><a class="nav-link link text-white display-4" href="code.html">Code</a></li><li class="nav-item"><a class="nav-link link text-white display-4" href="data.html">Data</a></li><li class="nav-item"><a class="nav-link link text-white display-4" href="graph.html">Knowledge Graph</a></li><li class="nav-item"><a class="nav-link link text-white display-4" href="queries.html">Queries</a></li></ul>
</div>
</nav>
</section>
<section class="engine"><a href="https://mobirise.info/u">bootstrap html templates</a></section><section class="mbr-section content4 cid-rvhKJA0ILc" id="content4-q">
<div class="container">
<div class="media-container-row">
<div class="title col-12 col-l-8">
<h2 class="align-center pb-3 mbr-fonts-style display-2"><strong>Code</strong></h2>
<h3 class="mbr-section-subtitle align-center mbr-light mbr-fonts-style display-5">The beauty of Python.</h3>
</br>
</br>
</br>
<p class="mbr-text mbr-fonts-style display-7">Scripting all our processes in <a href="https://www.python.org" class="text-info" target="_blank">Python</a> 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.</p>
<p class="mbr-text pb-2 mbr-fonts-style display-7">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 <a href="https://github.com/europinion/europinion.github.io/tree/master/scripts" class="text-info" target="_blank">GitHub</a> 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 <a href="https://saifmohammad.com/WebPages/NRC-Emotion-Lexicon.htm" class="text-info" target="_blank">NRC Word-Emotion Association Lexicon</a> (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 <a href="queries.html">Queries</a> you can find SPARQL scripts, which we used for querying our data.</p>
</div>
</div>
</div>
</section>
<section class="tabs2 cid-rvhLFeJf7A" id="tabs2-w">
<div class="container">
<div class="media-container-row">
<div class="col-12 col-l-8">
<ul class="nav pb-4 nav-tabs" role="tablist">
<li class="nav-item"><a class="nav-link mbr-fonts-style show active display-7" role="tab" data-toggle="tab" href="#tabs2-w_tab0" aria-selected="true">Acquiring</a></li>
<li class="nav-item"><a class="nav-link mbr-fonts-style show active display-7" role="tab" data-toggle="tab" href="#tabs2-w_tab1" aria-selected="true">Cleaning</a></li>
<li class="nav-item"><a class="nav-link mbr-fonts-style show active display-7" role="tab" data-toggle="tab" href="#tabs2-w_tab2" aria-selected="true">Translating</a></li>
<li class="nav-item"><a class="nav-link mbr-fonts-style show active display-7" role="tab" data-toggle="tab" href="#tabs2-w_tab3" aria-selected="true">Analysing</a></li>
</ul>
<div class="tab-content">
<div id="tab1" class="tab-pane in active" role="tabpanel">
<div class="row">
<div class="col-md-12">
<p class="pb-2 mbr-fonts-style display-7">We acquired the data by exploiting the <a href="https://developer.twitter.com/en.html" class="text-info" target="_blank">Twitter API</a>. 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 <a href="https://github.com/geduldig/TwitterAPI" class="text-info" target="_blank">TwitterAPI</a> library, and then we used the <a href="https://pandas.pydata.org" class="text-info" target="_blank">Pandas</a> library to store the tweets within a CSV file.</p> <p class="pb-2 mbr-fonts-style display-7">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.</p>
<pre>
<code class="python">
# -*- 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...')
</code>
</pre>
</div>
</div>
</div>
<div id="tab2" class="tab-pane" role="tabpanel">
<div class="row">
<div class="col-md-12">
<p class="pb-2 mbr-fonts-style display-7">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.</p>
<p class="pb-2 mbr-fonts-style display-7">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 <a href="https://pypi.org/project/tweet-preprocessor/" class="text-info" target="_blank">Tweet Preprocessor</a> 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 <a href="http://wit.istc.cnr.it/stlab-tools/sentilo/index.html" class="text-info" target="_blank">Sentilo</a>. The reduction was required because the communication with Sentilo employs HTTP GET requests, which have certain limitations.</p>
<pre>
<code class="python">
# -*- 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)
</code>
</pre>
</div>
</div>
</div>
<div id="tab3" class="tab-pane" role="tabpanel">
<div class="row">
<div class="col-md-12">
<p class="pb-2 mbr-fonts-style display-7">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.</p>
<p class="pb-2 mbr-fonts-style display-7">Most services like Google are monetising their APIs nowadays – analysing 9.000.000 characters with Google is not possible for a no-budget project (<a href="https://cloud.google.com/translate/pricing" class="text-info" target="_blank">$20/one million chr.</a>). The Russian company <a href="https://yandex.com" class="text-info" target="_blank">Yandex</a> offers a <a href="https://tech.yandex.com/translate/" class="text-info" target="_blank">Translate API</a>, 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.</p>
<pre>
<code class="python">
# -*- 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)
</code>
</pre>
</div>
</div>
</div>
<div id="tab4" class="tab-pane" role="tabpanel">
<div class="row">
<p class="pb-2 mbr-fonts-style display-7">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 <a href="graph.html">Knowledge Graph</a>. The flexible structure of a graph enables us to further enrich the data with future additions, like the <a href="http://saifmohammad.com/WebPages/lexicons.html#terms" class="text-info" target="_blank">Sentiment and Emotion Lexicons</a> by Saif M. Mohammad.</p>
<p class="pb-2 mbr-fonts-style display-7">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 <a href="https://github.com/RDFLib/rdflib" class="text-info" target="_blank">RDFLib</a> to add the data as triples (subject, predicate and object) to our named graph. The resulting file is an RDF/XML.</p>
<pre>
<code class="python">
# -*- 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)
</code>
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section once="footers" class="cid-rvh7pWUyp3" id="footer7-h">
<div class="container">
<div class="media-container-row align-center mbr-white">
<div class="row row-links">
<ul class="foot-menu">
<li class="foot-menu-item mbr-fonts-style display-7"><a href="contact.html" class="text-white"><strong>Contact</strong></a></li><li class="foot-menu-item mbr-fonts-style display-7"><a href="disclaimer.html" class="text-white"><strong>Disclaimer</strong></a></li><li class="foot-menu-item mbr-fonts-style display-7"><a href="references.html" class="text-white"><strong>References</strong></a></li>
</ul>
</div>
<div class="row row-copirayt">
<p class="mbr-text mb-0 mbr-fonts-style mbr-white align-center display-7">© Copyright 2019 Severin Josef Burg, Eleonora Peruch</p>
</div>
</div>
</div>
</section>
<script src="assets/web/assets/jquery/jquery.min.js"></script>
<script src="assets/popper/popper.min.js"></script>
<script src="assets/tether/tether.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/dropdown/js/nav-dropdown.js"></script>
<script src="assets/dropdown/js/navbar-dropdown.js"></script>
<script src="assets/touchswipe/jquery.touch-swipe.min.js"></script>
<script src="assets/mbr-tabs/mbr-tabs.js"></script>
<script src="assets/smoothscroll/smooth-scroll.js"></script>
<script src="assets/theme/js/script.js"></script>
</body>
</html>