2

我有一个具有以下格式的 csv 文件

Tampa Florida, Aarhus Denmark, Tampa Florida
Tampa Florida, Aarhus Denmark, London England, Tampa Florida

每行都是一次旅行,我需要计算每次旅行的总距离。我想我可以对纬度/经度坐标的每个位置进行地理编码,然后使用这些坐标在 geopy 中使用 vincenty 计算距离。我需要英里和公里的距离,我需要它写入 csv 文件,英里在 1 列中,公里在单独的列中。

Tampa Florida, Aarhus Denmark, Tampa Florida, XXX miles, XXX kilometers

到目前为止,我有以下代码,并花了两天时间研究解决方案,我想我不是一个很好的程序员,所以请帮忙:

from geopy.geocoders import ArcGIS
geolocator = ArcGIS()
import csv
with open('ttest.csv', "rb") as infile:
   reader = csv.reader(infile, delimiter=",")
   for row in reader:
      a=",".join(row)
      address, (latitude, longitude)=geolocator.geocode(a, timeout=10)
      print (address, latitude, longitude)

我试图最终完成的示例,尽管它不起作用。

list1 = ["Tampa, Florida", "Aarhus, Denmark"]
locations = list1
location = geolocator.geocode("locations", timeout=10)
print((location.latitude, location.longitude))
from geopy.distance import vincenty
x = list1[0]
y = list1[1]
Sum all distances in a row
print(vincenty(sum).miles)
print(vicenty(sum).kilometers)

我感谢任何和所有的帮助。

4

1 回答 1

0

我认为这应该可以解决您的问题。如果您还有其他问题,请不要犹豫。

import csv
from geopy.geocoders import ArcGIS
from geopy.distance import vincenty

geolocator = ArcGIS()

# data to write in file
new_rows_list = []

# read file and generate data to write back
with open('ttest.csv') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        trip = list(map(lambda x: geolocator.geocode(x), row))

        distanceKm = sum(list(map(lambda x, y: vincenty(x.point, y.point).km, trip[:-1], trip[1:])))
        distanceMiles = sum(list(map(lambda x, y: vincenty(x.point, y.point).miles, trip[:-1], trip[1:])))

        row.append(distanceKm)
        row.append(distanceMiles)

        new_rows_list.append(row)

# write back to file
with open('ttest.csv', newline='', mode='w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(new_rows_list)
于 2017-03-21T16:00:51.080 回答