-
Notifications
You must be signed in to change notification settings - Fork 0
added sentiment analysis with running compound score #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SChakravorti21
wants to merge
1
commit into
DisruptHC:master
Choose a base branch
from
SChakravorti21:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| from tweepy import Stream, OAuthHandler, StreamListener | ||
| import json | ||
| from datetime import * | ||
| import numpy as np | ||
| from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer | ||
| from pprint import pprint | ||
|
|
||
| timestamp = datetime.strftime(datetime.now(),"%Y%m%d%H%M%S") | ||
| analyzer = SentimentIntensityAnalyzer() | ||
|
|
||
| class listener(StreamListener): | ||
| global i, runningCompound | ||
| i = 1 | ||
| runningCompound = 0.0 | ||
|
|
||
| def on_data(self, data): | ||
| global i, runningCompound | ||
|
|
||
| try: | ||
| tweet = json.loads(data) | ||
| #print len(tweet),tweet['user']['screen_name'],tweet['text'] | ||
| #print tweet['user']['location'],tweet['user']['geo_enabled'],tweet['coordinates'],tweet['geo'],tweet['place'] | ||
|
|
||
| if isNotReply("in_reply_to_screen_name", tweet): | ||
|
|
||
| if len(tweets['no_reply'])<N*3: | ||
| tweets['no_reply'].append(tweet) | ||
| try: | ||
| sentence = str(tweet['text']) | ||
| print(sentence) | ||
| score = sentimentScore(sentence) | ||
| #print(score) | ||
| score = score.get('compound') | ||
| #print(score) | ||
| runningCompound = (runningCompound*(i-1) + score)/i | ||
| i = i + 1 | ||
|
|
||
| except Exception as inst: | ||
| print("Unable to print", inst.args) | ||
|
|
||
| else: | ||
| timestamp=datetime.strftime(datetime.now(),"%Y%m%d%H%M%S") | ||
| filename = path2+"dataset_noreply_%s.json"%timestamp | ||
| f=open(filename,'w') | ||
| json.dump(tweets['no_reply'],f, sort_keys=True, indent=4) | ||
| f.close() | ||
| tweets['no_reply'][:]=[] | ||
| print (N, "tweets", timestamp) | ||
| print("\n\n\n", "Running Compound Score: ", runningCompound, "\n\n\n") | ||
| #print len(tweets['no_reply']),tweet['user']['screen_name'],tweet['text'] | ||
|
|
||
| else: | ||
|
|
||
| if len(tweets['in_reply'])<N: | ||
| tweets['in_reply'].append(tweet) | ||
|
|
||
| try: | ||
| sentence = str(tweet['text']) | ||
| print(sentence) | ||
| # score = sentimentScore(sentence) | ||
| # #print(score) | ||
| # score = score.get('compound') | ||
| # #print(score) | ||
| # runningCompound = (runningCompound*(i-1) + score)/i | ||
| # i = i + 1 | ||
|
|
||
| except Exception as inst: | ||
| print("Unable to print", inst.args) | ||
|
|
||
|
|
||
| names['replyN'].append(tweet["in_reply_to_screen_name"]) | ||
| names['screenN'].append(tweet['user']['screen_name']) | ||
| else: | ||
| timestamp=datetime.strftime(datetime.now(),"%Y%m%d%H%M%S") | ||
|
|
||
| f2=open(path1+"dataset_edges_%s.json"%timestamp,'w') | ||
|
|
||
| for i in np.arange(len(names['replyN'])): | ||
| f2.write(names['screenN'][i] + "," + names['replyN'][i] + '\n') | ||
|
|
||
| f2.close() | ||
|
|
||
| f=open(path1+"dataset_reply_%s.json"%timestamp,'w') | ||
| json.dump(tweets['in_reply'],f) | ||
| f.close() | ||
| tweets['in_reply'][:]=[] | ||
| print (N, "tweets", timestamp) | ||
| #print 'Y', len(tweets['in_reply']),tweet['user']['screen_name'],tweet['text'] | ||
| #print len(tweet["in_reply_to_screen_name"]),tweet["in_reply_to_screen_name"] | ||
| #sprint | ||
|
|
||
| except Exception as inst: | ||
| print ("something happened", inst.args) | ||
|
|
||
| def on_error(self,status): | ||
| if status == 420: | ||
| # Returning False terminates the Stream to prevent incurring | ||
| # more errors. | ||
| return False; | ||
| print ("Error",status) | ||
|
|
||
|
|
||
| def isNotReply(string, tweet): | ||
| return (string not in tweet or tweet[string] == None or tweet[string] == 'null') | ||
|
|
||
| def sentimentScore(text): | ||
| return analyzer.polarity_scores(text) | ||
|
|
||
| N=50 | ||
| tweets={'in_reply':[],"no_reply":[]} | ||
| names={'replyN':[],"screenN":[]} | ||
| path1="Data1/" | ||
| path2="Data2/" | ||
| ConsumerKey="YpPSDUHum0regAT6vt390zRaR" | ||
| ConsumerSecret="0qpxgfv3SkD6GOZnIAxWVJA7TTewfFoVluPy8Dad5oKigQOxuZ" | ||
|
|
||
| AccessToken="2675842215-kXO7G1ZqaVo1hUcA2GUSmBz0Aupnfx5FLaZLvS7" | ||
| AccessTokenSecret="0HpMPy5z1APpsUyQgBBf9qm4eNmcFRFm1k65Nb8EU0CPB" | ||
|
|
||
| auth=OAuthHandler(ConsumerKey,ConsumerSecret) | ||
| auth.set_access_token(AccessToken, AccessTokenSecret) | ||
|
|
||
| twitterStream=Stream(auth, listener()) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Stream times out with "No such directory"
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sentiment analysis in real time on this data? |
||
|
|
||
| #track=["obama","trump"] | ||
| track=["war"] | ||
| [lon0,lat0,lon1,lat1]=[-74.1687,40.5722,-73.8062,40.9467] | ||
| twitterStream.filter(track=track,locations=[lon0,lat0,lon1,lat1]) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's pull access tokens from env variables or conf instead