1
Twitter Streaming API에 열린 연결을 유지하는 python 스크립트가 있고 json 파일에 데이터를 씁니다. 현재 파일이 특정 크기에 도달 한 후에 연결을 끊지 않고 새 파일에 쓸 수 있습니까? 예를 들어, 방금 1 주일 이상 데이터를 스트리밍했으나 모든 데이터가 단일 파일 (~ 2GB)에 포함되어 있기 때문에 구문 분석 속도가 느려집니다. 500MB라고 말한 후 새 파일에 쓸 수 있다면 하나의 큰 파일 대신 4 개의 작은 파일 (예 : dump1.json, dump2.json 등)을 파싱해야합니다.Python API 스트리밍, 특정 크기 이후에 새 파일 쓰기
import tweepy
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy.streaming import StreamListener
# Add consumer/access tokens for Twitter API
consumer_key = '-----'
consumer_secret = '-----'
access_token = '-----'
access_secret = '-----'
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
# Define streamlistener class to open a connection to Twitter and begin consuming data
class MyListener(StreamListener):
def on_data(self, data):
try:
with open('G:\xxxx\Raw_tweets.json', 'a') as f:
f.write(data)
return True
except BaseException as e:
print("Error on_data: %s" % str(e))
return True
def on_error(self, status):
print(status)
return True
bounding_box = [-77.2157,38.2036,-76.5215,39.3365]#filtering by location
keyword_list = ['']#filtering by keyword
twitter_stream = Stream(auth, MyListener())
twitter_stream.filter(locations=bounding_box) # Filter Tweets in stream by location bounding box
#twitter_stream.filter(track=keyword_list) # Filter Tweets in stream by keyword
'os.stat (tweet_file) .st_size> 2 ** 10' 파일 크기는 어떻게 설정합니까? –
@AndrewR. 이것은 파일 크기를 확인하는 방법입니다. 우선 예외를 피하기 위해 존재를 확인합니다. _try ... except_를 사용할 수 있습니다. 이 코드를 _getter_ 메소드에 패키지화 할 수 있습니다. – volcano