Python谷歌地图距离矩阵仅使用可接受的邮政编码



我使用谷歌距离矩阵来确定邮政编码之间的距离,然而,由于数据的性质,有时没有合法的邮政编码传递给API。谷歌仍然返回了一段距离。例如,它通过了";BLVD";作为邮政编码,它返回了3000英里。如果不是真正的zip,我如何告诉谷歌的api抛出错误?我找不到任何关于它的文档…任何有帮助的东西!非常感谢。

url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins={}&destinations={}&key={}"
# Get method of requests module
# return response object
r = requests.get(url.format(origin, dest, api_key))
# json method of response object
# return json format result
x = r.json()

如果将BLVD传递给它,JSON返回为

{'destination_addresses': ['205 SE Washington Blvd, Bartlesville, OK 74006, USA'], 
'origin_addresses': ['Eagle Mountain, UT 84043, USA'], 
'rows': [{'elements': [{'distance': {'text': '1,150 mi', 'value': 1850562},
'duration': {'text': '17 hours 25 mins', 'value': 62709}, 'status': 'OK'}]}], 
'status': 'OK'}

如果传递了一个真正的zip,JSON返回为

{'destination_addresses': ['Salt Lake City, UT 84116, USA'], 
'origin_addresses': ['Eagle Mountain, UT 84043, USA'], 
'rows': [{'elements': [{'distance': {'text': '42.4 mi', 'value': 68169}, 
'duration': {'text': '58 mins', 'value': 3496}, 'status': 'OK'}]}], 
'status': 'OK'}

感谢您的帮助!由于Google API没有任何东西可以表明是否是真正的zip,所以我决定创建自己的函数来验证它是否是zip。另一种可能性是使用https://pypi.org/project/zipcodes/使用函数is_real((。

isZip检查是否至少有5或10位数字长(对于带连字符的zip(,并确保每个字符都不是alpha

def isZip(zipcode):
if len(zipcode) != 5 and len(zipcode) != 10:
return False
for i in zipcode:
if i.isalpha() is True:
return False
return True

lzipcodes = ["90451", "BLVD", "54335-4555"] * 100
for zipcode in lzipcodes:
print(isZip(zipcode))

相关内容

最新更新