-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
93 lines (67 loc) · 2.72 KB
/
app.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
import tweepy
import requests
from textblob import TextBlob
import numpy as np
import matplotlib.pyplot as plt
import Apis
import json
# Comment out line 5
# If image is present with the current tweet, then this function downloads
# the Image and saves it to 'currentFolder/Images' directory
def photo_extracter(tweet):
try:
media_url = tweet.entities['media'][0]['media_url']
name = tweet.entities['media'][0]['id_str']
r = requests.get(media_url)
with open(f"Images/{name}.png", "wb") as f:
f.write(r.content)
except:
print('No media found')
# Function to analyse tweets
def func(search_query, n):
''' Delete Apis.ConsumerApiKey and Enter your consumer api key '''
Consumer_Api_Key = Apis.ConsumerApiKey
''' Delete Apis.ConsumerSecret and Enter your consumer secret '''
Consumer_Secret = Apis.ConsumerSecret
''' Delete Apis.AccessToken and Enter your access token '''
Access_Token = Apis.AccessToken
''' Delete Apis.AccessTokenSecret and Enter your access token secret '''
Access_Token_Secret = Apis.AccessTokenSecret
auth = tweepy.OAuthHandler(Consumer_Api_Key, Consumer_Secret)
auth.set_access_token(Access_Token, Access_Token_Secret)
api = tweepy.API(auth)
tweets = tweepy.Cursor(api.search, q=f'#{search_query}', tweet_mode = 'extended', lang='en', count = 100).items(n)
pos = 0
neg = 0
neu = 0
for tweet in tweets:
# print(tweet.entities['media'])
photo_extracter(tweet)
blob = TextBlob(tweet.full_text)
polarity = blob.sentiment.polarity
if polarity == 0:
neu += 1
elif polarity < 0.00:
neg += 1
elif polarity > 0.00:
pos += 1
pos_percentage = (pos/n)*100
neg_percentage = (neg/n)*100
neu_percentage = (neu/n)*100
print(f'{pos} persons tweeted positive, {neg} persons tweeted negative and {neu} persons were neutral')
pos_percentage = format(pos_percentage, '.2f')
neg_percentage = format(neg_percentage, '.2f')
neu_percentage = format(neu_percentage, '.2f')
# Plot using Matplotlib
label = [f'Positive [{str(pos_percentage)}%]', f'Negative [{str(neg_percentage)}%]', f'Neutral [{str(neu_percentage)}%]']
sizes = [pos, neg, neu]
colors = ['yellowgreen', 'blue', 'red']
patches, texts = plt.pie(sizes, colors=colors, startangle=90)
plt.legend(patches, label, loc = 'best')
plt.axis('equal')
plt.tight_layout()
plt.show()
if __name__ == "__main__":
search_query = input("Enter the hashtag you want to search for (without # keyword): ")
n = int(input('Enter number of tweets you want to analyse: '))
func(search_query, n)