我想从excel文件中读取大量坐标(约14000+),然后通过百度地图的API将它们转换成特定的地址。但程序只能读取最后一个坐标。我的代码有问题吗?这是我的密码:
import requests
import pandas as pd
import json
df = pd.read_excel(r'C:\Users\YDC\Desktop\JW.xlsx')
fw = open(r'C:\Users\YDC\Desktop\result.txt', "w", encoding="utf-8")
for i in range(0,len(df)):
t1=df.iloc[i]['lat']
t2=df.iloc[i]['lng']
baiduUrl = "http://api.map.baidu.com/geocoder/v2/?ak=21q0bMSgjdDVe0gLmjClrsuyUA1mvsRx&callback=renderReverse&location=%s,%s&output=json&pois=0" % (t1, t2)
req = requests.get(baiduUrl)
content = req.text
content = content.replace("renderReverse&&renderReverse(", "")
content = content[:-1]
baiduAddr = json.loads(content)
country = baiduAddr["result"]["addressComponent"]["country"]
city = baiduAddr["result"]["addressComponent"]["city"]
province = baiduAddr["result"]["addressComponent"]["province"]
new_line = country + "|" + city + "|" + province
fw.write(new_line)
fw.write("\n")
print(new_line)
只能打印最后一个坐标的地址: 捷克共和国
如何得到其余的坐标? Here is the data in excel file
这看起来像是一个经典的python循环
考虑一下:
输出
这是因为在python中,变量范围是这样的:您仍然可以从循环外部引用在循环内部定义的变量
一个非常简单的修复方法如下:
给出了预期的结果
在您的情况下,只需确保第12行以后的行向右缩进一级
相关:Scoping in Python 'for' loops
相关问题 更多 >
编程相关推荐