Search code examples
python-3.xtwitter-oauthtweepysentiment-analysistextblob

Is there a reason why the following code does not execute (print the tweets) after taking input?


So basically I want to print a set number of tweets related to a topic that user enters but when I run the following code after giving in the input nothing happens, I see no output after that. I would be really grateful if you could tell me why :-)

I tried regenerating the access token keys and then again copy pasting it but the problem still persists

import tweepy
consumerKey = "Sgdz0quGjDDTtGbFAxWQ02E5M"
consumerSecret = "alphanumeric"
accessToken = "980878168180609024-nggEvf3WSLb1IcmmHfoCMhDNvZjbMid"
accessTokenSecret = "alpha numeric"

auth = tweepy.OAuthHandler(consumer_key=consumerKey, 
consumer_secret=consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)
api = tweepy.API(auth)

searchTerm = input("Enter keyword/hashtag to search about : ")
number = int(input("How many tweets do you wanna print :  "))
tweets = tweepy.Cursor(api.search, q=searchTerm, lang= "English").items(number)

for tweet in tweets:
    print(tweet.text)

this is what my console is showing after execution

runfile('C:/users/acer/.spyder-py3/temp.py', wdir='C:/users/acer/.spyder-py3')

Enter keyword/hastag to search about : bts

How many tweets do you wanna print :  5

In [14]:

(It does not print the tweets)


Solution

  • Your language needs to be "en". This works:

    searchTerm = input("Enter keyword/hashtag to search about : ")
    number = int(input("How many tweets do you wanna print :  "))
    
    print ("Tweets with ", searchTerm, ": ")
    
    for result in tweepy.Cursor(api.search, q=searchTerm, lang="en").items(number):
      print( result.text)
    

    Results of a test run:


    Python 3.7.4 (default, Jul 9 2019, 00:06:43) [GCC 6.3.0 20170516] on linux

    Enter keyword/hashtag to search about : kendrick

    How many tweets do you wanna print : 2

    Tweets with kendrick :

    RT @flwrrb0y: them: you can’t even dance to kendrick lamar

    me: RT @Blaqboimagic: Calling Kendrick overrated is unacceptable