2
\$\begingroup\$

I had done this program that takes an input from STDIN and processes it to check if it is a Latitude/longitude combo or a place's name. Then it uses geocoding and returns an address corresponding to the latitude longitude or returns a latitude and longitude if the input is an address. I am using Nomatim, I would like to know how else can we do this?I would also like to know how I can make the code better.

from geopy.geocoders import Nominatim
import re
geolocator=Nominatim()
arg=raw_input()
pattern=re.compile(r'^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$')
if pattern.match(arg):
    loc=geolocator.reverse(arg)
    if loc is not None:
        print(loc.address)
        print(loc.latitude, loc.longitude)
    else:
        print "the location doesnt exist"
else:
    loc=geolocator.geocode(arg)
    if loc is not None:
        print(loc.address)
        print(loc.latitude, loc.longitude)
    else:
        print "This address does not exist"
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Duplicated code

You should try to follow the Don't Repeat Yourself principle. In your case, most of the logic is repeated in 2 branches.

You could write :

if pattern.match(arg):
    loc=geolocator.reverse(arg)
else:
    loc=geolocator.geocode(arg)
if loc is not None:
    print(loc.address)
    print(loc.latitude, loc.longitude)
else:
    print "the location doesnt exist"

Alternatively, this could be written using conditional expressions :

loc = geolocator.reverse(arg) if pattern.match(arg) else geolocator.geocode(arg)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.