首页 > 解决方案 > 如何修复'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

我收到该错误的代码有什么问题?

谢谢!

标签: pythongeopy

解决方案


这是使用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.


推荐阅读