语法无效的原因未知

时间:2013-06-27 16:51:05

标签: python api weather

我不明白为什么会收到“无效语法”错误。我做了一个小时的研究没有成功。我正在运行PYTHON 3.此代码中的语法错误在哪里?

  from urllib.request import urlopen
  import json

  request = urlopen("http://api.aerisapi.com/observations/Urbandale,IA?client_id=QD2ToJ2o7MKAX47vrBcsC&client_secret=0968kxX4DWybMkA9GksQREwBlBlC4njZw9jQNqdO")
  response = request.read().decode("utf-8")
  json = json.loads(response)
  if json['success']:
      ob = json['respnose']['ob']
      print ("the current weather in urbandale is %s with a temperature of %d") % (ob['weather'].lower(), ob['tempF']
 else
      print "An error occurred: %s" % (json['error']['description'])
 request().close 

3 个答案:

答案 0 :(得分:8)

有几个原因:

  1. 您的括号不平衡:

    print ("the current weather in urbandale is %s with a temperature of %d") % (ob['weather'].lower(), ob['tempF']
    

    这是一个关闭的括号,而你所拥有的那个是错误的位置。

    这应该是:

    print ("the current weather in urbandale is %s with a temperature of %d" % (ob['weather'].lower(), ob['tempF']))
    
  2. 您的else语句缺少:冒号。

  3. 你的第二个print函数不是函数,它假装是Python 2语句。通过添加括号来纠正它:

    print("An error occurred: %s" % (json['error']['description']))
    
  4. 您的缩进似乎不正确,但这可能是发布错误。

  5. 您的最后一行也无效;您想拨打close(),而不是request()

    request.close()
    

    使用urllib,您无需关闭对象。

  6. 你拼错了respnose

    ob = json['response']['ob']
    
  7. 工作代码:

    from urllib.request import urlopen
    import json
    
    request = urlopen("http://api.aerisapi.com/observations/Urbandale,IA?client_id=QD2ToJ2o7MKAX47vrBcsC&client_secret=0968kxX4DWybMkA9GksQREwBlBlC4njZw9jQNqdO")
    response = request.read().decode("utf-8")
    json = json.loads(response)
    if json['success']:
        ob = json['response']['ob']
        print("the current weather in urbandale is %s with a temperature of %d" % (ob['weather'].lower(), ob['tempF']))
    else:
        print("An error occurred: %s" % (json['error']['description']))
    

答案 1 :(得分:2)

:之后需要else;

else:
      print "An error occurred: %s" % (json['error']['description'])

此行上()的数量不相等:

>>> strs = """print ("the current weather in urbandale is %s with a temperature of %d") % (ob['weather'].lower(), ob['tempF']"""
>>> strs.count('(')
3
>>> strs.count(')')
2

if-else应正确缩进:

if json['success']:
    ob = json['respnose']['ob']
    print ("the current weather in urbandale is %s with a temperature of %d") % (ob['weather'].lower(), ob['tempF'])
else:
    print "An error occurred: %s" % (json['error']['description'])

答案 2 :(得分:0)

该行

print ("the current weather in urbandale is %s with a temperature of %d") % (ob['weather'].lower(), ob['tempF']

缺少结束)

应该是

print ("the current weather in urbandale is %s with a temperature of %d" % (ob['weather'].lower(), ob['tempF']))

Python可能会在 next

中抱怨它