-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtwitter_sentiment.py
68 lines (41 loc) · 1.19 KB
/
twitter_sentiment.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
import csv
import tweepy
from textblob import TextBlob
def Tweep():
consumer_key = ''
consumer_secret = ''
access_token = ''
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 the 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 a topic to search: ')
# Generate file
give_me_csv(user, topic)
if __name__ == '__main__':
main()