2015-01-24 16 views
5

Tôi có một tập lệnh làm việc tập hợp thành công các tweet đề cập đến "stackoverflow". Tuy nhiên, tôi muốn chạy kịch bản trong iPython (thay vì điều hành một tệp .py riêng biệt). Lý tưởng nhất, tôi chỉ muốn mở tập tin ipyb, chọn chạy tất cả, và để nó chạy trong một tuần hoặc lâu hơn (không đóng máy tính xách tay của tôi) và kết quả là tôi có một tập tin .json với giá trị của một tuần.Làm thế nào để lưu một dòng Twitter tweepy vào một tập tin?

Dưới đây là những gì tôi có cho đến nay:

from tweepy import Stream 
from tweepy import OAuthHandler 
from tweepy.streaming import StreamListener 

access_token = "x" 
access_token_secret = "x" 
consumer_key = "x" 
consumer_secret = "x" 

# file name that you want to open is the second argument 
save_file = open('data.json', 'a') 

class listener(StreamListener): 

    def on_data(self, data): 
     print(data) 
     return True 

    def on_error(self, status): 
     print(status) 

auth = OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_token, access_token_secret) 
twitterStream = Stream(auth, listener()) 
twitterStream.filter(track=["stackoverflow"]) 

Trả lời

5

thêm đoạn mã sau vào mã hiện tại của bạn. 'fetched_tweets.txt' là tên của tệp mà bạn muốn lưu các tweet được mở trong 'a' (chế độ nối thêm).

class StdOutListener(StreamListener): 

    def on_data(self, data): 
     #print data 
     with open('fetched_tweets.txt','a') as tf: 
      tf.write(data) 
     return True 

    def on_error(self, status): 
     print status 
2

bạn có thể làm điều đó với sản lượng chuyển hướng vào một tập tin

python twitter_streaming.py > twitter_data.txt 

cho phụ nộp sử dụng >>

Các vấn đề liên quan