Skip to main content
 首页 » 编程设计

python之反向地理编码,读取 .CSV 文件和 TypeError : a float is required

2024年10月17日39leader

修正:为坐标 1 和坐标 2 添加了 float():

my_location = gmaps.reverse_geocode(float(coordinates1), float(coordinates2)) 

我正在尝试将经纬度坐标转换为地址。我有一个带有坐标的 .CSV 文件,但我不知道我的代码是否可以读取它,或者它是否有其他错误。 这是我的代码:

from pygeocoder import Geocoder 
import csv 
 
gmaps = Geocoder(api_key='api-key') 
 
input = open('C:/Users/Steffen/PycharmProjects/untitled/sadist.csv','r') 
output = open('C:/Users/Steffen/PycharmProjects/untitled/distsaretailer.csv', 'w') 
 
try: 
reader = csv.reader(input) 
writer = csv.writer(output) 
 
for row in reader: 
    print(row) 
    coordinates1 = row[0] 
    coordinates2 = row[1] 
 
    my_location = gmaps.reverse_geocode(coordinates1,coordinates2) 
 
    writer.writerow(my_location) 
 
finally: 
input.close() 
output.close() 

错误信息:

Traceback (most recent call last): 
  File "C:/../latlongs.py", line 22, in <module> 
    my_location = gmaps.reverse_geocode(coordinates1,coordinates2) 
 
  File "C:\..\pygeocoder.py", line 155, in reverse_geocode 
    'latlng':   "%f,%f" % (lat, lng), 
['69.9687376', '23.2715496'] 
TypeError: a float is required 

请您参考如下方法:

正如 PM 2Ring 指出的那样,您需要将坐标从字符串转换为 float 。替换:

coordinates1 = row[0] 
coordinates2 = row[1] 

与:

coordinates1, coordinates2 = [float(c) for c in row]