@TristanIsaac/

project-GevoelensAnalyseTristan&Aryan

Python

No description

fork
loading
Files
  • main.py
  • Gevoelensanalyse_chart.png
  • Gevoelensanalyse_lijst.csv
  • requirements.txt
main.py
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
import os
import sys
import csv
import tweepy
import matplotlib.pyplot as plt

from collections import Counter
from aylienapiclient import textapi

open_kwargs = {}

if sys.version_info[0] < 3:
    input = raw_input
else:
    open_kwargs = {'newline': ''}


# API sleutels
# Twitter
consumer_key = "U0XDrgMEgpg0AQHmnZNUuqq1T"
consumer_secret = "XJeGX4T0X05RXyB2dxCJzUxYwfnH0SsF3Edh6f35ANZbEknYrm"
access_token = "64766943-x2sqCqMF7BNDFmWpSI3c00Xm1wefGMtQOWMUxA7or"
access_token_secret = "j9qMYJL3WrC12YPkM6cxWHQsbCd5r1tGNMoAQBViWp60J"

# AYLIEN
#Codes Tristan
application_id = '01c25138'
application_key = '2020f9b925ea27cd5dc199d6c6b17a98'
#Codes Aryan
#application_id  = '0e3dfb53'
#application_key = '8ae333ef4e34614acb285e4b0e0c2e75'

# Opstart tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

# Opstart aylien
client = textapi.Client(application_id, application_key)

#Aanmaak CSV bestand (voor lijst tweets en sentiment)
max_id = 0 #Tweets krijgen een ID (het eerste getal in de CSV), dit lijntje geeft aan vanaf welke Tweet we analyzeren (0 neemt de recentste tweets)

file_name = 'Gevoelensanalyse_lijst.csv'

if os.path.exists(file_name):
    with open(file_name, 'r') as f:
        for row in csv.DictReader(f):
            max_id = row['Tweet_ID']
else:
        with open(file_name, 'w', **open_kwargs) as f:
            csv.writer(f).writerow([
                                    "Tweet_ID",
                                    "Time",
                                    "Tweet",
                                    "Sentiment"])
#Vraagstelling onderwerp en aantal Tweets
Q=input("Welk onderwerp wilt u analyseren?\n")
C=input("Hoeveel tweets wilt u analyseren?\n")
results = api.search(
    lang="en", #Ondersteunde talen voor Aylien Sentiment Analysis: Engels (en), Duits (de) en Spaans (es) 
    q=Q + " -rt", #Kies hier je onderwerp
    result_type="mixed", #Typ zoekresultaten, mogelijkheden: mixed, recent & popular
    count=C, #aantal tweets om te analyseren, maximum 100
    since_id=max_id
)
#creates anonymous function
results = sorted(results, key=lambda x: x.id)

print("--- Je opgevraagde Tweets zijn verzameld, analyse wordt uitgevoerd...  ---")

#Deze lijnen code verzamelen de tweets in de CSV
with open(file_name, 'a', **open_kwargs) as csvfile:
    csv_writer = csv.DictWriter(
        f=csvfile,
        fieldnames=[
                    "Tweet_ID",
                    "Time",
                    "Tweet",
                    "Sentiment"]
    )

    #print("--- CSV aangemaakt... --- \n")

    #kuis de Tweets verzend ze naar de AYLIEN Text API
    for c, result in enumerate(results, start=1):
        tweet = result.text
        tidy_tweet = tweet.strip().encode('ascii', 'ignore')
        tweet_time = result.created_at
        tweet_id = result.id

        if not tweet:
            print('Tweet is ongeldig')
            continue

        #print(tidy_tweet)
        response = client.Sentiment({'text': tidy_tweet})
        csv_writer.writerow({
        	"Tweet_ID": tweet_id,
        	"Time": tweet_time,
            'Tweet': response['text'],
            'Sentiment': response['polarity'],
        })
       
        #print("{}e Tweet is geanalyseerd".format(c))

print ("--- Gevoelensanalyse is voltooid... Diagram word aangemaakt... ---")
#Aanmaak diagram
with open("Gevoelensanalyse_lijst.csv") as data:
    counter = Counter()
    for row in csv.DictReader(data):
        counter[row['Sentiment']] += 1 #bij traceback error, herlaad de pagina

    positive = counter['positive']
    negative = counter['negative']
    neutral = counter['neutral']

# declare the variables for the pie chart, using the Counter variables for "sizes"
colors = ['green', 'red', 'lightgrey']
sizes = [positive, negative, neutral]
labels = 'Positive', 'Negative', 'Neutral'

# use matplotlib to plot the chart
plt.pie(
    x=sizes,
    shadow=False,
    colors=colors,
    #labels=labels,
    startangle=90,
    autopct='%1.0f%%',
    )
patches, texts = plt.pie(sizes, colors=colors, startangle=90)
plt.legend(patches, labels, loc="best")
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.tight_layout()
plt.show()

plt.savefig('Gevoelensanalyse_chart')