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))
您應該嘗試'print(line)'來查看它是否看起來像JSON。 – Delgan
輸出是: { 「貢獻者」:空, 然後Traceback錯誤。 – Darcava
這裏是你的問題:'{「contributors」:null'不是有效的JSON格式,所以'json.loads()'失敗。'test.json'的數據格式不適合你的代碼,你應該確保每行只有一個JSON對象,或者您可以重寫您的解析函數。 – Delgan