python - 如何修复'TypeError:'ArcGIS'类型的参数在geopy上不可迭代'错误?
问题描述
我想制作一个程序,您可以在其中输入您的地址(代码中的示例是荷兰地址),然后程序给出该地址的经度和纬度作为输出。我还尝试使它更加用户友好,所以如果输入的地址不存在,程序会这样说。代码是:
from geopy.geocoders import ArcGIS
nom = ArcGIS()
adres = input("enter your adress as folows:\n 32 Gunterstein, Amsterdam, 1081 CJ\n vul in: ")
n = nom.geocode(adres)
if adres in nom:
print("longitude:",n.longitude)
print("latitude:", n.latitude)
else:
print("adress doesn't exist, please try again.")
print("end")
如果用户输入有效地址,则代码有效,但是当我通过输入废话来尝试时,我收到以下错误:
enter your adress as folows:
32 Gunterstein, Amsterdam, 1081 CJ
vul in: nonsense
Traceback (most recent call last):
File "breede_en_lengte_graden.py", line 7, in <module>
if adres in nom:
TypeError: argument of type 'ArcGIS' is not iterable
我收到该错误的代码有什么问题?
谢谢!
解决方案
这是使用try-except
块执行此操作的一种方法:
try:
print("longitude:", n.longitude)
print("latitude:", n.latitude)
except AttributeError:
print("adress doesn't exist, please try again.")
print("end")
你也可以用一个if-else
块来做,但你必须做的有点不同:
if n is not None:
print("longitude:", n.longitude)
print("latitude:", n.latitude)
else:
print("adress doesn't exist, please try again.")
print("end")
进行这种检查的原因是nom.geocode(adres)
不会在无效地址上失败,而是简单地返回None
并分配n
.
推荐阅读
- r - 在 R、Linux 中使用“mclapply”进行并行计算
- python - 创建矩阵,用 numpy 反射给定矩阵的属性
- c++ - C++ - 获取该类用作另一个模板的模板的类型名
- flutter - SocketException:操作系统错误:对等方重置连接,errno = 54,地址 = 192.168.178.117,端口 = 52699
- java - Spring Boot 运行 java: java.lang.NullPointerException 没有错误描述,intellij Mac OS Catalina
- python - 从与另一列中的某些值对应的列中选择 pandas (Python) 中的值
- c# - 打开时切换 v-expansion-panel-header 上的图标
- r - 将数据框中的字符列转换为日期
- python - 使用 pandas 和 seaborn 绘制分钟和每小时数据的箱线图
- android - Android Real Time developer notification for one time purchase is half working