2015-05-26 40 views
0

我正在使用Twitter Streaming API來獲取與特定關鍵字匹配的推文。獲得的輸出寫入文件。我根據鳴叫發起的距離做一些基本的比較,然後相應地寫入單獨的文件。Twitter Streaming API Python - 將不完整的數據寫入文件

 lat2=float(d['geo']['coordinates'][0]) 
     long2=float(d['geo']['coordinates'][1]) 
     lat1=venue_latitude 
     long1=venue_longitude 
     lon1, lat1, lon2, lat2 = map(radians, [long1, lat1, long2, lat2]) 
     dlon = lon2 - lon1 
     dlat = lat2 - lat1 
     a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 
     c = 2 * asin(sqrt(a)) 
     distance = 6367 * c * 0.621371 
     if distance < 1: 
      user= d['user']['screen_name'] 
      user_id=d['user']['id'] 
      file=open('Tweets_within_one_mile.txt','a') 
      users.append(user) 
      text=str(user) + str(user_id)+ "qwertyasdfgzxcvb" + str(distance) + d['text'] 
      u = text.encode('utf-8') 
      file.write(u) 
      file.close() 
     if distance > 2 and distance < 60: 
      user= d['user']['screen_name'] 
      user_id=d['user']['id'] 
      file=open('Tweets_within_sixty_miles.txt','a') 
      users.append(user) 
      text=str(user) + str(user_id) + str(co_lon2) +d['text'] 
      u = text.encode('utf-8') 
      file.write(u) 
      file.close() 

當我最後一次運行腳本時。收集的推文數量達到30,000條。但只有2萬條推文完整地寫入了該文件。其餘的一萬個是不完整的。

Python輸出緩衝區有問題嗎?

回答

0

我不能確定這是爲什麼只有他們的一部分被保存的確切原因,但你構建你的if語句的方式可能與它有關。

例如:

if distance < 1: 
    print("foo") 

if distance > 2 or distance a < 60: 
    print("bar") 
  1. 該代碼工作爲值更少,但不等於1
  2. 1和2之間的數字將不工作(即,1.1至1.9)
  3. 編號等於2或60張
  4. 數大於60

阿加在,不確定的確切值你試圖獲得,但也許這可能會有所幫助(它會捕獲所有的數據):

if distance <= 1: 
    print("foo") 

if 2 <=distance or distance <= 60: 
    print("bar")