将JSON转换为GeoJSON的问题

时间:2016-04-22 21:39:04

标签: python json twitter geojson

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

除了迭代方法之外,一切似乎都在运行 - 当脚本运行时,它会将所有推文输出到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))

1 个答案:

答案 0 :(得分:0)

迭代正在运作;问题是Twitter返回的样本中缺少地理编码的推文。通过更大的搜索范围或更具包容性的查询字词解决。