-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitter_til_geojson.py
91 lines (80 loc) · 4.03 KB
/
twitter_til_geojson.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""
Koden er bygget på koden fra pensumboken Mastering Social Media Mining with Python av Marco Bonzanini
Original koden kan finnes på https://github.com/bonzanini/Book-SocialMediaMiningPython/blob/master/Chap02-03/twitter_make_geojson.py
"""
import json
from argparse import ArgumentParser
def get_parser():
parser = ArgumentParser()
parser.add_argument('--tweets')
parser.add_argument('--geojson')
parser.add_argument('--point', default = False)
return parser
if __name__ == '__main__':
parser = get_parser()
args = parser.parse_args()
with open(args.tweets, 'r') as f:
geo_data = {
"type": "FeatureCollection",
"features": []
}
for line in f:
tweet = json.loads(line)
try:
if tweet['coordinates']:
geo_json_feature = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": tweet['coordinates']['coordinates']
},
"properties": {
"text": tweet['text'],
"created_at": tweet['created_at'],
"location": tweet['user']['location']
}
}
geo_data['features'].append(geo_json_feature)
if tweet['place'] is not None:
if args.point == False:
geo_json_feature = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates":[[
[tweet['place']['bounding_box']['coordinates'][0][0][0], tweet['place']['bounding_box']['coordinates'][0][0][1]],
[tweet['place']['bounding_box']['coordinates'][0][1][0], tweet['place']['bounding_box']['coordinates'][0][1][1]],
[tweet['place']['bounding_box']['coordinates'][0][2][0], tweet['place']['bounding_box']['coordinates'][0][2][1]],
[tweet['place']['bounding_box']['coordinates'][0][3][0], tweet['place']['bounding_box']['coordinates'][0][3][1]]
]]
},
"properties": {
"text": tweet['text'],
"created_at": tweet['created_at'],
"location": tweet['user']['location']
}
}
geo_data['features'].append(geo_json_feature)
else:
xcenter = (tweet['place']['bounding_box']['coordinates'][0][0][0] - tweet['place']['bounding_box']['coordinates'][0][2][0])/2
ycenter = (tweet['place']['bounding_box']['coordinates'][0][0][1] - tweet['place']['bounding_box']['coordinates'][0][1][1])/2
geo_json_feature = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates":[
xcenter + tweet['place']['bounding_box']['coordinates'][0][2][0],
ycenter + tweet['place']['bounding_box']['coordinates'][0][1][1]
]
},
"properties": {
"text": tweet['text'],
"created_at": tweet['created_at'],
"location": tweet['user']['location']
}
}
geo_data['features'].append(geo_json_feature)
except KeyError:
continue
with open(args.geojson, 'w') as fout:
fout.write(json.dumps(geo_data, indent=4))