语法无效的原因不明

app*_*723 -4 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 
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 8

几个原因:

  1. 你的括号不平衡:

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

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

    这应该是:

    print ("the current weather in urbandale is %s with a temperature of %d" % (ob['weather'].lower(), ob['tempF']))
    
    Run Code Online (Sandbox Code Playgroud)
  2. 你的else陈述缺少:冒号.

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

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

  5. 你的最后一行也无效; 你想打电话close(),而不是request():

    request.close()
    
    Run Code Online (Sandbox Code Playgroud)

    有了urllib,你真的不需要关闭对象.

  6. 你错了拼写respnose:

    ob = json['response']['ob']
    
    Run Code Online (Sandbox Code Playgroud)

工作代码:

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']))
Run Code Online (Sandbox Code Playgroud)