0

使用 Python 2.6,当我运行下面的脚本时会发生以下错误:

Traceback (most recent call last):
  File "g.py", line 7, in <module>
    results  = Geocoder.geocode(row[0])
  File "/usr/lib/python2.6/site-packages/pygeocoder.py", line 261, in geocode
    return GeocoderResult(Geocoder.getdata(params=params))
  File "/usr/lib/python2.6/site-packages/pygeocoder.py", line 223, in getdata
    raise GeocoderError(j['status'], url)
pygeocoder.GeocoderError: Error ZERO_RESULTS
Query: http://maps.google.com/maps/api/geocode/json?region=&sensor=false&bounds=&language=&address=%22++A+FAKE+ADDRESS

Python 2.6 脚本:

import csv, string
from pygeocoder import Geocoder

with open('file.csv') as goingGeo:
        theSpreadsheet = csv.reader(goingGeo, quotechar=None)
        for row in theSpreadsheet:
                results  = Geocoder.geocode(row[0])
                (lat, long) = results[0].coordinates
                with open('geo_file.csv', 'a') as f:
                        f.write(row[0] + ",")
                        f.write(row[1] + ",")
                        f.write(row[2] + ",")
                        f.write(row[3] + ",")
                        f.write(row[4] + ",")
                        f.write(row[5] + ",")
                        f.write(row[6] + ",")
                        f.write(row[7] + ",")
                        try:
                                f.write(str(lat))
                        except GeocoderError:            
                                pass
                        f.write(",")
                        try:
                                f.write(str(long))
                        except GeocoderError:            
                                pass
                        f.write('\n')

我只希望脚本即使出现错误也能继续。

谢谢!

4

4 回答 4

1

write您在不可能抛出 GeoCoderError 的调用周围有 try/except 块,但在调用周围没有 try/exceptgeocoder()可以(并且显然确实)抛出该错误。你可能想要这样的东西:

try:
    results  = Geocoder.geocode(row[0])
    (lat, long) = results[0].coordinates
except GeocoderError:
    (lat, long) = (0.0, 0.0)
于 2013-04-27T01:58:39.687 回答
0

像这样使用 try-except-finally 语句:

try:
    f.write(str(lat))
except GeocodeError:
    pass
finally:
    do_something_else_regardless_of_above
于 2013-04-27T01:59:20.227 回答
0

您在try: except GeocoderError零件的正确轨道上,但它们在错误的位置。您需要移动它们来包装Geocoder.geocode调用,因为这就是引发错误的原因:

        for row in theSpreadsheet:
                try:
                        results  = Geocoder.geocode(row[0])
                except GeocoderError:
                        continue
                (lat, long) = results[0].coordinates

另请注意,您需要importGeocoderError. pygeocoder此外,long是 Python 中的一个关键字,所以我建议为该变量选择一个不同的名称。

于 2013-04-27T01:59:26.070 回答
0
#starting from line 6:
for row in theSpreadsheet:
        try:
            results  = Geocoder.geocode(row[0])
        except:
            pass
#rest of script . . .

你也可以使用“except”来处理特定的错误。

try:
    results=Geocoder.geocode(row[0])
except GeocodeError:
    #deal with error
于 2013-04-27T02:01:27.963 回答