我希望使用Google API搜索位置在Python中自动执行任务。现在,我的Google Maps API代码正在为一组地理坐标返回“医院”。
但是,我有一个包含许多地理坐标的CSV文件。
1: Hanoi,10.762622,106.660172
2: Ho Chi Minh,12.762622,108.660175
3: Ho Chi Minh,11.8542,108.660175
4: ...
5: ...
正如您在我的代码中看到的那样,这样做效率不高,因为我需要手动更改地理坐标。
对于我的CSV文件中的每一行(地理坐标),我希望我的代码读取地理坐标1:Hanoi并为此地理坐标提供结果“医院”。在读取第2行:胡志明和所有其他行相同。
如何才能实现这样或任何使这样的任务更有效的好例子?
import urllib
import urllib.request
import json
googleGeocodeUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query='
keyword = "hospital"
geolocation = "&location=-12.135,-77.023&radius=5000"
APIKEY = '&key='+'apikey'
url = googleGeocodeUrl + keyword + geolocation + APIKEY
print(url)
url = googleGeocodeUrl + keyword + geolocation + APIKEY
json_response = urllib.request.urlopen(url)
search = json_response.read().decode('utf-8')
searchjson = json.loads(search)
export = open('hopital.csv','w')
for place in searchjson['results']:
print(place['name'])
print(place['geometry']['location'])
export.write(place['name']+','+str(place['geometry']['location']['lng'])\
+','+str(place['geometry']['location']['lat'])+'\n')
export.close()
答案 0 :(得分:0)
您可以使用Python标准库中包含的csv
库来实现此目的。
具体而言,csv.DictReader()和csv.writer()
csv.DictReader()
示例:
import csv
with open('places.csv', newline='') as f:
reader = csv.DictReader(f, fieldnames=["place", "longitude", "latitude"])
places = [row for row in reader]
for row in places:
# your code here
csv.writer()
示例:
import csv
with open('hopital.csv','w', newline='') as f:
writer = csv.writer(f)
for place in searchjson['results']:
writer.writerow([place['name'],
str(place['geometry']['location']['lng']),
str(place['geometry']['location']['lat'])])
此外,您还可以使用urllib.parse.urlencode()从参数和值的字典中自动生成参数字符串。
答案 1 :(得分:0)
利用Python的csv
库来帮助您阅读和编写CSV文件。另外,最好使用格式字符串来帮助将变量插入到URL中:
import csv
import urllib
import urllib.request
import json
googleGeocodeUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query={}&location={},{}&radius=5000&key={}'
keyword = "hospital"
key = '123'
with open('input.csv', newline='') as f_input, open('hospital.csv', 'w', newline='') as f_output:
csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)
csv_output.writerow(['Search place', 'Name', 'Lat', 'Long'])
for search_place, lat, long in csv_input:
url = googleGeocodeUrl.format(urllib.parse.quote(search_place), lat, long, key)
json_response = urllib.request.urlopen(url)
search = json_response.read().decode('utf-8')
searchjson = json.loads(search)
for place in searchjson['results']:
row = [place['name'], place['geometry']['location']['lng'], place['geometry']['location']['lat']]
csv_output.writerow(row)
格式字符串使用功能强大的迷你语言,但最简单的方法是,只需添加{}
作为占位符即可替换。对于使用的每个{}
,格式在调用时将其替换为匹配的参数,例如
'test{}'.format(123)
'lat is {}, long is {}'.format(123, 456)