-4

我不明白为什么会收到“无效语法”错误。我做了一个小时的研究,没有成功。我正在运行 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 
4

3 回答 3

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']
    

工作代码:

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']))
于 2013-06-27T16:52:47.350 回答
2

你需要一个:after 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'])
于 2013-06-27T16:52:32.680 回答
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 可能会在下一行抱怨它

于 2013-06-27T16:52:24.373 回答