2016-01-24 95 views
1

我目前正在撰写一个搜索天气的程序。 我试图创建一个选项,您可以搜索您的位置,但它似乎并没有工作。Wunderground api搜索栏

from urllib.request import Request, urlopen 
    import json 
    import re 
    location = input('location you would like to know the weather for') 

API_KEY = '<API-KEY>' 
url = 'http://python-weather-api.googlecode.com/svn/trunk/ python-weather-api' + API_KEY +'/geolookup/conditions/q/IA/'+ location +'.json' 


response = urllib.request.Request(url) 


def response as request(url) 
json_string = response.read().decode('utf8') 
parsed_json = json.loads(json_string) 
location = parsed_json['location']['city'] 


temp_f = parsed_json['current_observation']['temp_f'] 
print("Current temperature in %s is: %s" % (location, temp_f)) 
response.close() 

我一直在recieving此错误

回答

0

如果你已经str.input,你需要使用STR(位置)。现在,如果你进入python repl并键入str,你会发现它是一个保留关键字。你想使用从用户输入而不是str对象获得的变量位置。

+0

好,谢谢,它似乎解决这个问题,但是我会收到另一个说明'urllib'未定义的问题。 – user3541130

1

不能评论(声誉太低,因为我刚加入SO),但关于你的“urllib没有定义”的问题,这与你如何导入urlopen函数有关。

相反的:

urllib.urlopen(url) 

尝试:

urlopen(url) 

编辑:这是你的代码,固定:

from urllib.request import urlopen 
import json 

location = input('location you would like to know the weather for') 

API_KEY = '<API-KEY>' 
url = 'http://api.wunderground.com/api/' + API_KEY + '/geolookup/conditions/q/IA/'+ str(location) +'.json' 

response = urlopen(url) 

json_string = response.read().decode('utf8') 
parsed_json = json.loads(json_string) 
location = parsed_json['location']['city'] 
temp_f = parsed_json['current_observation']['temp_f'] 
print("Current temperature in %s is: %s" % (location, temp_f)) 

工作正常的多摩,在IA其他城市。不过请注意,Des Moines这样的地名将无法使用,因为URL中不允许有空格 - 您必须注意这一点。 (API的示例建议_用于空间http://www.wunderground.com/weather/api/d/docs?MR=1)。祝你好运!

+0

我试过这个,但是它回来的错误是 NameError:name'response'没有被定义 – user3541130

+0

这是因为你没有把你的urlopen(url)分配给任何东西。提示:请求= urlopen(url) – zebralove79

+0

我没有为urlopen错误。我有这个作为我的错误 json_string = response.read()。decode('utf8') NameError:name'response'is not defined – user3541130