我不明白为什么会收到“无效语法”错误。我做了一个小时的研究没有成功。我正在运行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
答案 0 :(得分:8)
有几个原因:
您的括号不平衡:
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']))
您的else
语句缺少:
冒号。
你的第二个print
函数不是函数,它假装是Python 2语句。通过添加括号来纠正它:
print("An error occurred: %s" % (json['error']['description']))
您的缩进似乎不正确,但这可能是发布错误。
您的最后一行也无效;您想拨打close()
,而不是request()
:
request.close()
使用urllib
,您无需关闭对象。
你拼错了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']))
答案 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 行
中抱怨它