首先让我说我是Python的新手,并且在编程方面经验很少。 我决定在我的工作中使用Python作为一些工作自动化的环境。 我需要对导出到XLS,地理编码地址的一些日期进行排序,然后在Google API地图或OpenSourceMaps上创建热图/人口地图。 SOme解决方案我已经找到但是有问题将它们组合起来,并且处于非常错误的阶段。
请看我的代码:
import os
import pandas
import geopy
import urllib
import csv
import numpy
import geopy
# - - - - - - - - -
fin = open ("source_file.csv","r") # open input file for reading
users_dict = {}
with open('output_file.csv', 'wb') as fout: # output csv file
writer = csv.writer(fout)
with open('source_file.csv','r') as csvfile: # input csv file
reader = csv.DictReader(csvfile, delimiter=',')
for row in reader:
location_string = row['city'] + ',' + row['street'] + ' ' + row['house']
from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.geocode(location_string)
row['lat']=latitude = location.latitude
row['lng'] = location.longitude
users_dict.update(row)
print (users_dict)
fout.close()
fin.close()
输入文件格式
unit_no,kod,street,house,city,lng,lat
123456,00-001,nowy swiat,4,warszawa,,
字典输出:
{'unit_no': '123456', 'kod': '00-001', 'street': 'nowy swiat', 'house': '4', 'city': 'warszawa', 'lng': 21.0220598, 'lat': 52.2302825}
结果: output_file.csv为零大小 打开的output_file.csv在
中没有显示任何内容包含数据的预期输出文件:
unit_no,kod,street,house,city,lng,lat
123456,00-001,nowy swiat,4,warszawa,21.0220598,52.2302825
在我看来,下一步是从创建的输出创建geojson文件,然后在地图上将其标记或填充可视化。
提前感谢您提出有价值的建议。
答案 0 :(得分:0)
制作标题列表并首先在output_file.csv中写入
header = ['unit_no','kod','street','house','city','lng','lat']
writer.writerow(header)
这将使csv的头第一行,然后输出字典每次都与csv的第一行相关,并相应地添加数据。
答案 1 :(得分:0)
如果我理解你的话我的代码应该是这样的:
with open('output_file.csv', 'wb') as fout: # output csv file
writer = csv.writer(fout)
header = ['unit_no','kod','street','house','city','lng','lat'] # your suggestion
writer.writerow(header) # your suggestion
with open('source_file.csv','r') as csvfile: # input csv file
并完成:
print (users_dict)
writer = csv.DictWriter(fout, delimiter=',') # your suggestion
writer.writerows(user_dict) # your suggestion
fout.close()