Advertisement
mdan

tweet_shit

Jan 23rd, 2018
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.51 KB | None | 0 0
  1. import re
  2. import tweepy
  3. from tweepy import OAuthHandler
  4. from textblob import TextBlob
  5. import matplotlib.pyplot as plt
  6.  
  7. class Tweet_shit(object):
  8.    
  9.     def __init__(self):
  10.  
  11.         #Aici va puneti propriile credentiale
  12.         consumer_key = '//////'
  13.         consumer_secret = '//////'
  14.         access_token = '//////'
  15.         access_token_secret = '/////////'
  16.  
  17.         try:
  18.             self.auth = OAuthHandler(consumer_key, consumer_secret)        
  19.             self.auth.set_access_token(access_token, access_token_secret)        
  20.             self.api = tweepy.API(self.auth)
  21.        
  22.         except:
  23.             print("Error: Authentication Failed")
  24.  
  25.     def curata_tweet(self, tweet):
  26.         return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
  27.        
  28.        
  29.     def get_tweet_sentiment(self, tweet):
  30.    
  31.         analysis = TextBlob(self.clean_tweet(tweet))
  32.         if analysis.sentiment.polarity > 0:
  33.             return 'positive'
  34.         elif analysis.sentiment.polarity == 0:
  35.             return 'neutral'
  36.         else:
  37.             return 'negative'
  38.  
  39.     def get_tweets(self, query, count = 100):
  40.  
  41.         tweets = []
  42.  
  43.         try:
  44.             fetched_tweets = self.api.search(q = query, count = count)
  45.             for tweet in fetched_tweets:
  46.                 parsed_tweet = {}
  47.                 parsed_tweet['text'] = tweet.text
  48.                 parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)
  49.  
  50.                 if tweet.retweet_count > 0:
  51.                     if parsed_tweet not in tweets:
  52.                         tweets.append(parsed_tweet)
  53.                 else:
  54.                     tweets.append(parsed_tweet)
  55.  
  56.             return tweets
  57.  
  58.         except tweepy.TweepError as e:
  59.             print("Error : " + str(e))
  60.  
  61. def main():
  62.     api = TwitterClient()
  63.     tweets = api.get_tweets(query = 'Klaus Iohannis', count = 200)
  64.     ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
  65.     print("Procent tweet-uri pozitive: {} %".format(100*len(ptweets)/len(tweets)))
  66.     ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
  67.     print("Procent tweet-uri negative: {} %".format(100*len(ntweets)/len(tweets)))
  68.     etweets = [tweet for tweet in tweets if tweet['sentiment'] == 'neutral']
  69.     netweets = len(ntweets) + len(ptweets)
  70.     neutraltweets = len(tweets) - netweets
  71.     q = neutraltweets / len(tweets)
  72.    
  73.    
  74.     print ("Procent tweet-uri neutre: {} %" .format(100*q))
  75.     print("\n\nPositive tweets:")
  76.     for tweet in ptweets[:10]:
  77.         print(tweet['text'])
  78.  
  79.  
  80.     print("\n\nNegative tweets:")
  81.     for tweet in ntweets[:10]:
  82.         print(tweet['text'])
  83.  
  84.  
  85.     print("\n\nNeutral tweets")
  86.     for tweet in etweets[:10]:
  87.         print(tweet['text'])
  88.  
  89.     print('Neutre: ', len(etweets))
  90.     print('Pozitive: ', len(ptweets))
  91.     print('Negative: ', len(ntweets))
  92.    
  93.     fig = plt.figure()
  94.    
  95.     labels = 'Neutre', 'Pozitive', 'Negative'
  96.     sizes = [len(etweets), len(ptweets), len(ntweets)]
  97.     colors = ['gold', 'yellowgreen', 'lightcoral']
  98.     explode = (0.1, 0, 0)
  99.     plt.legend(patches, labels, loc="lower right")
  100.     plt.title('Tweet-uri referitoare la Klaus Iohannis')
  101.    
  102.     plt.pie(sizes, explode=explode, labels=labels, colors=colors,
  103.         autopct='%1.1f%%', shadow=True, startangle=140)
  104.  
  105.     plt.axis('equal')
  106.     plt.show()
  107.     fig.savefig('Klaus_Iohannis')
  108.     plt.close()
  109.  
  110.  
  111. if __name__ == "__main__":
  112.  
  113.     main()
  114.    
  115.     #Succes!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement