Reputation: 533
I am trying to filter real-time tweets from twitter, I have this list keywords=["Alex", "love","hate","hungry","happy"] I want to get tweets that has "Alex" and at least one keyword from given list. my code is below when I run it, it tracks the tweet that contains any words from the list. remember again I want "Alex" as the main tracking keyword, tweet should have "Alex" and at least one of those words "love","hate","hungry","happy".
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
# consumer key, consumer secret, access token, access secret.
ckey = "xxxxxxxxxxxxxxx"
csecret = "xxxxxxxxxxxxxxxxxx"
atoken = "xxxxxxxxxxxxxxxxxx"
asecret = "xxxxxxxxxxxxxxxxxxx"
class listener(StreamListener):
def on_data(self, data):
all_data = json.loads(data)
tweet = all_data["text"]
username = all_data["user"]["screen_name"]
out = open('out1.txt', 'a')
out.write(tweet.encode('utf-8'))
out.write('\n')
out.close()
print username, " :: ", tweet
return True
def on_error(self, status):
print status
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
keywords = ["Alex", "love","hate","hungry","happy"]
twitterStream = Stream(auth, listener())
twitterStream.filter(track=keywords, languages=["en"])
Upvotes: 0
Views: 3607
Reputation: 884
Let's say you store your tweet in a variable named tweet
keywords = ['love', 'hate', 'hungry', 'happy']
if "Alex" in tweet:
if any(keyword in tweet for keyword in keywords):
# get the tweet
Upvotes: 2