Hi, MingyangPan
Tweepy’s on_data() method gives us a bit raw data. So Tweepy provides useful handlers methods such as on_status(), on_event(), etc. In your case, you don’t have to use on_data(), just use on_status() method.
I’d like to write code to do what your code intends like this code:
follow_acc = ['759251'] #cnn id
track_words = ['New Zealand flag'] # if remove ReTweets, add '-RT' in the word
class Listener(StreamListener):
def on_status(self, status):
with open('twitDB11.txt', 'a') as f:
# status.created_at is datetime object and status.text is the tweet's text
text = '::'.join([str(status.created_at), status.text, status.author.screen_name]) + '\n'
f.write(text)
if __name__ == '__main__':
twitterStream = Stream(auth, Listener())
twitterStream.filter(follow= follow_acc, track = track_words)
By running this code, I got twitDB11.txt which contains:
2015-12-18 17:04:05::RT @CNN: Just In: #StarWars: #TheForceAwakens has record $57 million opening night https://t.co/rCl9XK8Nwq https://t.co/RQz0Y38tvR::sddphoto
2015-12-18 17:04:08::@CNN Overhyped crap!!!::garrybluenose
2015-12-18 17:04:09::RT @CNN: Just In: #StarWars: #TheForceAwakens has record $57 million opening night https://t.co/rCl9XK8Nwq https://t.co/RQz0Y38tvR::imbernad88
2015-12-18 17:04:11::RT @CNN: Just In: #StarWars: #TheForceAwakens has record $57 million opening night https://t.co/rCl9XK8Nwq https://t.co/RQz0Y38tvR::SageOmar
2015-12-18 17:04:14::@CNN Just another point of view on stormtroopers...https://t.co/XWnniCiep5::tvn2884
2015-12-18 17:04:16::RT @CNN: Just In: #StarWars: #TheForceAwakens has record $57 million opening night https://t.co/rCl9XK8Nwq https://t.co/RQz0Y38tvR::Josh_B65
2015-12-18 17:04:16::RT @CNN: .@SenAngusKing: "A mistake" for @POTUS to downplay possible attack https://t.co/IPRP4vZ0p2 https://t.co/NFr2wlq1xy::PMorris153