1

I'm trying to create a bit of code to listen certain keywords on Twitter and am struggling to get the results I want.

I'm using Python 3.4.3.

Here's what I have that's working so far...


import tweepy
from time import sleep 
CONSUMER_KEY = 'abcabcabc'
CONSUMER_SECRET = 'abcabcabc'
ACCESS_KEY = 'abcabcabc'
ACCESS_SECRET = 'abcabcabc'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
auth.secure = True
api = tweepy.API(auth)

class MyStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        try:
            print(status.text)
        except:
            print("false")

myStreamListener = MyStreamListener
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener())


myStream.filter(track=['Cycling', 'Running'])

I'm trying to an if and elif statements to print different results depending on if the Tweet is Cycling or Running. I've used this code, but can't get it to work...


class MyStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        if 'Cycling' in myStreamListener:
            print('Cyclist' + status.text)
        elif 'Running' in myStreamListener:
            print('Runner' + status.text)
        else:
            print('false' + status.text)

myStreamListener = MyStreamListener
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener())


myStream.filter(track=['Cycling', 'Running'])

I can get the if & elif to work offline when not adding the complexity of Tweepy into the equation, but am confused about exactly how to use the in statement.

I'm new to Python so will more than likely be making some simple mistakes!

Any help would be greatly appreciated,

Many thanks,

Matt

1 Answers1

0

You are using in with the wrong variable (which points to the listener function). Use the status variable instead:

if 'cycling' in status.text.lower():
    print('Cyclist' + status.text)

Note that I added .lower() to the end of status.text. That way it will match the word 'cycling' regardless of if it is capitalised or not.

CaptSolo
  • 1,771
  • 1
  • 16
  • 17
  • Thank you for your help. The code worked and does what I wanted. I seem to be getting a coding error now but will open a new thread if I can't solve it... UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 69-69: Non-BMP character not supported in Tk –  Mar 09 '16 at 08:19
  • Regarding that error see http://stackoverflow.com/questions/32442608/python-error-ucs-2-codec-cant-encode-characters-in-position-1050-1050 – CaptSolo Mar 09 '16 at 08:49