通过使用geopy执行python脚本而出错

时间:2019-03-08 11:33:09

标签: python 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

出现该错误的代码有什么问题?

谢谢!

2 个答案:

答案 0 :(得分:1)

这是使用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的值。

答案 1 :(得分:0)

我认为它不会在错误的地址上引发错误。

n = nom.geocode('sdf324uio')
n is None
  

只需检查n是否为None即可查看是否向其传递了有效地址。

编辑:

有趣的是,实际上nonsense作为地方存在,并且它返回一个有效的位置(这是我第一次尝试输入不存在的地址):

n = nom.geocode('nonsense')
n
  

位置(无意义,(-23.56400999999994,-46.66579999999993,0.0))