2016-04-22 58 views
0

我的代码应该收集与给定查询相关的推文,将它们输出到JSON文件,然后迭代该JSON文件以提取信息并将输出格式化为geoJSON以导入到QGIS。将JSON转换为GeoJSON的困难

除了迭代方法之外,一切似乎都在发挥作用 - 脚本运行时,它会将所有推文输出到JSON,但它只会从JSON文件中拖出一条推文放入geoJSON文件。 代码如下:

# Imports Twython API client authorization, json library 
import json 
import tweepy 
from tweepy import OAuthHandler 

# API connection via Tweepy 

# Defines the API Consumer Key and Secret used to authenticate with Twitter 
API_KEY = 'API key' 
API_SECRET = 'API Secret' 
TOKEN_KEY = 'Token Key' 
TOKEN_SECRET = 'Token Secret' 

auth = OAuthHandler(API_KEY, API_SECRET) 
auth.set_access_token(TOKEN_KEY, TOKEN_SECRET) 

api = tweepy.API(auth) 
# Stores pulled tweets to .json file 
def tstore(tweet): 
    out_file = open("test.json","a") 
    json.dump(tweet, out_file) 
    out_file.write("\n") 
    out_file.close() 

for tweet in tweepy.Cursor(api.search, 
          q="#Lakers", 
          count=100, 
          geocode="33.7683,-118.1955,25mi").items(): 
    tstore(tweet._json) 
print "Done with Cursor" 


with open('test.json', 'r') as f: 
    line = f.readline() 
    geo_data = { 
     "type": "FeatureCollection", 
     "features": [] 
    } 
    for line in f: 
     tweet = json.loads(line) 
     if tweet['coordinates']: 
      geo_json_feature = { 
       "type": "Feature", 
       "geometry": tweet['coordinates'], 
       "properties": { 
        "text": tweet['text'], 
        "created_at": tweet['created_at'] 
       } 
      } 
      geo_data['features'].append(geo_json_feature) 
print "Next Stage" 
# Save geo data 
with open('geo_data.json', 'w') as fout: 
    fout.write(json.dumps(geo_data, indent=4)) 
+0

您应该尝试'print(line)'来查看它是否看起来像JSON。 – Delgan

+0

输出是: { “贡献者”:空, 然后Traceback错误。 – Darcava

+0

这里是你的问题:'{“contributors”:null'不是有效的JSON格式,所以'json.loads()'失败。'test.json'的数据格式不适合你的代码,你应该确保每行只有一个JSON对象,或者您可以重写您的解析函数。 – Delgan

回答

0

迭代运行;这个问题是由Twitter推出的样本缺乏地理编码推文。通过更大的搜索半径或更具包容性的查询条件解决。