-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsentiment_analysis.py
More file actions
71 lines (41 loc) · 1.3 KB
/
sentiment_analysis.py
File metadata and controls
71 lines (41 loc) · 1.3 KB
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
import csv
import tweepy
from textblob import TextBlob
def Tweep():
consumer_key = 'YOUR CONSUMER KEY'
consumer_secret = 'YOUR SECRET KEY'
access_token = 'YOUR ACCESS TOKEN'
access_token_secret = 'ACCESS TOKEN SECRET'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth)
def labeling(text):
blob = TextBlob(text).sentiment
if blob.subjectivity == 0:
return 0 # if no subjectivity we wont use tweet
else:
return 'Positive' if blob.polarity > 0 else 'Negative'
def give_me_csv(user, topic):
list_of_tweets = user.search(topic, count = 100)
filename = 'twitter_sentiment_%s.csv' % topic.replace(' ','')
with open(filename, 'w') as file:
fieldnames = ['tweet', 'sentiment_score']
writer = csv.DictWriter(file, fieldnames = fieldnames)
writer.writeheader()
for tweet in list_of_tweets:
tweet_text = tweet.text.encode('utf-8')
score = labeling(tweet.text)
if score != 0:
writer.writerow({
'tweet' : tweet_text,
'sentiment_score' : score
})
def main():
#Login Twitter
user = Tweep()
#ask topic
topic = raw_input('Enter topic to search:')
#generate file
give_me_csv(user, topic)
if __name__ == '__main__':
main()