Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Dec 22, 2023. It is now read-only.

Commit 5e66e80

Browse files
committed
Twitter Sentiment Analysis based on hashtag
1 parent 52bb21b commit 5e66e80

File tree

5 files changed

+176
-0
lines changed

5 files changed

+176
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
## Twitter Sentiment Analyis
2+
3+
### This script fetches 500 most recent tweets based on a single hashtag input, classifies the tweets based on sentiment polarity of either 'Positive', 'Negative' or 'Neutral' and writes the output to a .xls script.
4+
5+
### Pre-requisites
6+
7+
This script uses the twitter API called tweepy. For this you will require a set of access token and consumer keys. Following steps show you how to obtain these credentials:
8+
– Login to twitter developer section
9+
– Go to "Create an App"
10+
– Fill the details of the application.
11+
– Click on Create your Twitter Application
12+
– Details of your new app will be shown along with consumer key and consumer secret.
13+
– Click on "Create my access token" to obtain access token.
14+
15+
### How to use this script?
16+
17+
1. Make sure all the requirements for the script are present in your system by running:
18+
19+
pip install -r requirements.txt
20+
21+
2. Enter the following values in 'credentials.yaml' based on access/consumer tokens obtained above:
22+
- consumer_key
23+
- consumer_secret
24+
- access_token
25+
- access_token_secret
26+
27+
3. Run the following command (replace #hashtag with # of your choice):
28+
29+
python twitter_sentiment_analysis.py #hashtag
30+
31+
3. Open Sentiment_Analysis.xls to see analysed and categorised tweets
32+
33+
### Author
34+
35+
[Schezeen Fazulbhoy](https://github.com/schezfaz)
94 KB
Binary file not shown.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
consumer_key: ''
2+
consumer_secret: ''
3+
access_token: ''
4+
access_token_secret: ''
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
atomicwrites==1.4.0
2+
attrs==19.3.0
3+
autogui==0.1.8
4+
certifi==2020年6月20日
5+
chardet==3.0.4
6+
click==7.1.2
7+
colorama==0.4.3
8+
comtypes==1.1.7
9+
idna==2.10
10+
joblib==0.16.0
11+
more-itertools==8.4.0
12+
MouseInfo==0.1.3
13+
nltk==3.5
14+
oauthlib==3.1.0
15+
packaging==20.4
16+
Pillow==7.2.0
17+
pluggy==0.13.1
18+
py==1.9.0
19+
PyAutoGUI==0.9.50
20+
pycparser==2.20
21+
PyGetWindow==0.0.8
22+
PyMsgBox==1.0.8
23+
pyparsing==2.4.7
24+
pyperclip==1.8.0
25+
PyRect==0.1.4
26+
PyScreeze==0.1.26
27+
PySocks==1.7.1
28+
pytest==5.4.3
29+
pythonnet==2.5.1
30+
PyTweening==1.0.3
31+
pywin32==228
32+
pywinauto==0.6.8
33+
PyYAML==5.3.1
34+
regex==2020年9月27日
35+
requests==2.24.0
36+
requests-oauthlib==1.3.0
37+
six==1.15.0
38+
textblob==0.15.3
39+
tqdm==4.50.0
40+
tweepy==3.9.0
41+
urllib3==1.25.10
42+
wcwidth==0.2.5
43+
xlwt==1.3.0
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import re
2+
import sys
3+
import tweepy
4+
import yaml
5+
import xlwt
6+
from tweepy import OAuthHandler
7+
from textblob import TextBlob
8+
9+
10+
class TwitterClient(object):
11+
def __init__(self):
12+
"""
13+
Class constructor: Authentication via twitter API keys
14+
"""
15+
with open(r'credentials.yaml') as file:
16+
cred = yaml.load(file, Loader=yaml.FullLoader)
17+
18+
consumer_key = cred['consumer_key']
19+
consumer_secret = cred['consumer_secret']
20+
access_token = cred['access_token']
21+
access_token_secret = cred['access_token_secret']
22+
23+
# attempting authentication
24+
try:
25+
self.auth = OAuthHandler(consumer_key, consumer_secret)
26+
self.auth.set_access_token(access_token, access_token_secret)
27+
self.api = tweepy.API(self.auth)
28+
except:
29+
print("Error: Authentication Failed")
30+
31+
def clean_tweet(self, tweet):
32+
"""
33+
Removing links/special characters to clean up tweet
34+
"""
35+
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t]) | (\w+:\ / \ / \S+) ", " ", tweet).split())
36+
37+
def get_tweet_sentiment(self, tweet):
38+
"""
39+
Classifying tweet as Positive/Negative/Neutral using textblob's sentiment function
40+
"""
41+
analysis = TextBlob(self.clean_tweet(tweet))
42+
if analysis.sentiment.polarity > 0:
43+
return 'positive'
44+
elif analysis.sentiment.polarity == 0:
45+
return 'neutral'
46+
else:
47+
return 'negative'
48+
49+
def get_tweets(self, hashtag):
50+
"""
51+
Fetching & parsing 500 tweets based on hashtag
52+
"""
53+
all_tweets = []
54+
search_words = hashtag
55+
56+
try:
57+
tweets = tweepy.Cursor(self.api.search,
58+
q=search_words,
59+
lang="en",
60+
result='recent').items(500)
61+
for tweet in tweets:
62+
all_tweets.append(tweet.text)
63+
64+
return all_tweets
65+
66+
except tweepy.TweepError as e:
67+
print("Error : " + str(e))
68+
69+
70+
def main():
71+
api = TwitterClient()
72+
hashtag = sys.argv[1]
73+
all_tweets = api.get_tweets(hashtag)
74+
75+
#creating dictionary of tweet + sentiment
76+
wb = xlwt.Workbook(encoding='utf-8')
77+
style_head = xlwt.easyxf('pattern: fore_colour green; font: colour black, bold True;align: wrap yes; align: horiz center')
78+
style_rows = xlwt.easyxf('align: wrap yes; align: horiz center')
79+
sheet = wb.add_sheet('Analysed Tweets')
80+
sheet.col(0).width = 256 * 50
81+
sheet.col(1).width = 256 * 20
82+
sheet.write(0, 0, 'TWEET',style_head)
83+
sheet.write(0, 1, 'CLASSIFICATION',style_head)
84+
85+
86+
for i in range(0,len(all_tweets)):
87+
sheet.write((i+1),0, all_tweets[i],style_rows)
88+
sheet.write((i+1),1, api.get_tweet_sentiment(all_tweets[i]),style_rows)
89+
90+
wb.save('Sentiment_Analysis.xls')
91+
92+
93+
if __name__ == "__main__":
94+
main()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /