如果列表索引超出范围,则打印

时间:2015-12-04 23:51:57

标签: python-2.7 error-handling

大家好我试图为“列表索引超出范围”创建句柄但似乎没有任何运气。

import json, urllib, re
from urllib import urlencode
import googlemaps
import tempfile
import win32api
import win32print
start = "Adelaide, South Australia"
finish = " ghkjffzh, south Australia "



url = 'http://maps.googleapis.com/maps/api/directions/json?%s' % urlencode((
            ('origin', start),
            ('destination', finish)
 ))
ur = urllib.urlopen(url)
result = json.load(ur)
filename = "output.txt"
with open(filename, 'w') as output:
                for i in range(0, len(result['routes'][0]['legs'][0]['steps'])):
                    try:
                        s = (result['routes'][0]['legs'][0]['steps'][i]['html_instructions'])
                        d = (result['routes'][0]['legs'][0]['steps'][i]['distance']['text'])
                        l = (result['routes'][0]['legs'][0]['steps'][i]['duration']['text'])
                        s = re.sub('<[A-Za-z\/][^>]*>', '', s)
                        output.writelines(s + " " + d + " " + l + '\n')
                    except Exception:
                                print "Directions could not be printed"
                                output.write("Directions could not be given due to the format of page or the address type")

但没有任何内容写入.txt但仍然会出错。

我试图将 Exception 替换为 IndexError VauleError ,但没有更改

1 个答案:

答案 0 :(得分:1)

通过浏览返回的json结果解决了问题,并找到了 Status 结果,所以我首先通过了。

with open(filename, 'w') as output: 
     if result ['status'] == "NOT_FOUND"
      output.write( " no directions avalible")
     else:
       for i in range(0, len(result['routes'][0]['legs'][0]['steps'])): 
          s = (result['routes'][0]['legs'][0]['steps'][i]['html_instructions']) 
          d = (result['routes'][0]['legs'][0]['steps'][i]['distance']['text']) 
          l = (result['routes'][0]['legs'][0]['steps'][i]['duration']['text'])
          s = re.sub('<[A-Za-z\/][^>]*>', '', s)
          output.writelines(s + " " + d + " " + l + '\n')