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

标签 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并仍然出现错误。

香港专业教育学院试图用IndexError和VauleError替换Exception但没有变化

最佳答案

通过探索返回的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')

关于python-2.7 - 如果列表索引超出范围,则打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34099428/

相关文章:

python-2.7 - 在 mac osx 10.9 上安装 pyobjc

python-3.x - 如何使用 pandas 获取某种格式的表格并导出为 csv?

error-handling - 使用 Box<error::Error> 装箱后如何处理不同的错误类型?

swift - 如何在通过 Firebase (Swift) 创建用户之前检查电子邮件是否已被使用以及电子邮件格式是否错误

python - 实际上什么时候应该在Python中使用try-except?

python - 为什么即使我没有指定分隔符,split 函数也会忽略 '\n'?

python - Python的数学错误?

python - 语法错误 : Non-ASCII character '\xe2'

c++ - 无法使用 C++ catch(...) 捕获访问冲突异常

计算圆柱体面积和体积的 Java 运行时错误