Skip to content

Commit 8754b52

Browse files
committed
completed basic sentiment analysis function
1 parent b6d64db commit 8754b52

File tree

1 file changed

+49
-14
lines changed

1 file changed

+49
-14
lines changed

app.py

+49-14
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
auth = OAuthHandler(consumer_key, consumer_secret)
1515
auth.set_access_token(access_token, access_secret)
1616

17-
number_tweets_to_get = 20
17+
number_tweets_to_get = 1
1818

1919
api = tweepy.API(auth)
2020

@@ -45,26 +45,61 @@ def grabTweets(results):
4545
# print(clean_text)
4646

4747
#count positive words in a single cleaned tweet
48-
def countPositiveWords():
49-
#split all tweets into a list of words
50-
lines = open('tweets.txt', 'rb').readlines()
48+
def countPositiveWords(line):
5149
positiveWords = set(line.strip() for line in open('positiveW.txt'))
5250

5351
#find matches of positive words in the tweet
52+
words = line.split()
53+
count = 0
54+
for word in words:
55+
if word in positiveWords:
56+
count+=1
57+
return count
58+
59+
#count negative words in a single cleaned tweet
60+
def countNegativeWords(line):
61+
negativeWords = set(line.strip() for line in open('negativeW.txt'))
62+
63+
#find matches of positive words in the tweet
64+
words = line.split()
65+
count = 0
66+
for word in words:
67+
if word in negativeWords:
68+
count+=1
69+
return count
70+
71+
72+
73+
#calculates sentiment for a single tweet
74+
def calcSentiment(num):
75+
76+
#split all tweets into a list of words
77+
lines = open('tweets.txt', 'rb').readlines()
78+
totalSentiment = 0
5479
for line in lines:
55-
words = line.split()
56-
count = 0
57-
for word in words:
58-
if word in positiveWords:
59-
count+=1
60-
print count
61-
80+
num_pos_words = countPositiveWords(line)
81+
num_neg_words = countNegativeWords(line)
82+
if ((num_neg_words == 0) & (num_pos_words == 0)):
83+
sentiment = 0
84+
else :
85+
sentiment = float(num_pos_words - num_neg_words)/float(num_pos_words + num_neg_words)
86+
totalSentiment += sentiment
87+
averageSentiment = totalSentiment/num
88+
print averageSentiment
89+
6290

6391

6492
def main():
65-
results = tweepy.Cursor(api.user_timeline, screen_name=sys.argv[1]).items(number_tweets_to_get)
66-
grabTweets(results);
67-
countPositiveWords()
93+
#results = tweepy.Cursor(api.user_timeline, screen_name=sys.argv[1]).items(number_tweets_to_get)
94+
# The search term you want to find
95+
query = sys.argv[1]
96+
# Language code (follows ISO 639-1 standards)
97+
language = "en"
98+
#number of tweets to get
99+
num = 100
100+
results = api.search(q=query, lang=language, count=num)
101+
grabTweets(results)
102+
calcSentiment(num)
68103

69104

70105
# # The search term you want to find

0 commit comments

Comments
 (0)