-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
95 lines (77 loc) · 3.08 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
94
95
import numpy as np
import joblib
from flask import Flask, render_template, request
import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob
class TwitterClient(object):
def __init__(self):
consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
try:
self.auth = OAuthHandler(consumer_key, consumer_secret)
self.auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(self.auth)
except:
print("Error: Authentication Failed")
def get_tweet_sentiment(self, tweet):
analysis = TextBlob(tweet)
if analysis.sentiment.polarity > 0:
return 'Positive'
elif analysis.sentiment.polarity == 0:
return 'Neutral'
else:
return 'Negative'
def get_tweets(self, query, count=200):
tweets = []
try:
fetched_tweets = self.api.search(q=query, count=count)
for tweet in fetched_tweets:
parsed_tweet = {}
parsed_tweet['text'] = tweet.text
parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)
if tweet.retweet_count > 0:
if parsed_tweet not in tweets:
tweets.append(parsed_tweet)
else:
tweets.append(parsed_tweet)
return tweets
except tweepy.TweepError as e:
print("Error : " + str(e))
def clean_data(token):
return [item for item in token if
not item.startswith('@') and not item.startswith('http') and not item.startswith("RT")]
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def home():
return render_template('index.html')
@app.route("/search", methods=["GET", "POST"])
def result():
if request.method == "POST":
api = TwitterClient()
query = str(request.form.get("query"))
tweets = api.get_tweets(query=query, count=25)
for tweet in tweets:
my_list = tweet["text"].split()
for item in range(len(my_list)):
new_list = clean_data(my_list)
tweet["text"] = " ".join(new_list)
pos_cnt, neg_cnt = 0, 0
for tweet in tweets:
if tweet["sentiment"] == "Positive":
pos_cnt += 1
elif tweet["sentiment"] == "Negative":
neg_cnt += 1
return render_template('index.html', your_list=tweets, pos_cnt=pos_cnt, neg_cnt=neg_cnt, count=len(tweets),
query=query)
@app.route("/java", methods=["GET", "POST"])
def java():
return render_template("mood_java.html")
@app.route("/python", methods = ["GET", "POST"])
def python():
return render_template("mood_python.html")
if __name__ == "__main__":
app.run(debug=True)