这个问题怎么了?

2024-04-25 11:42:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从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


Tags: importjsoncitydfnewlineresultcontent
1条回答
网友
1楼 · 发布于 2024-04-25 11:42:20

这看起来像是一个经典的python循环

考虑一下:

for i in range(0, 10):
    foo = i
print (foo) # notice the indentation 

输出

9

这是因为在python中,变量范围是这样的:您仍然可以从循环外部引用在循环内部定义的变量

一个非常简单的修复方法如下:

for i in range(0, 10):
    foo = i
    print (foo)

给出了预期的结果

0
1
2
3
4
5
6
7
8
9

在您的情况下,只需确保第12行以后的行向右缩进一级

相关:Scoping in Python 'for' loops

相关问题 更多 >