我现在正在写一个搜索天气的程序。我正在尝试创建一个选项,你可以搜索你的位置,但它似乎不起作用。
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()我一直收到这个错误
发布于 2016-01-25 01:20:21
现在还不能评论(因为我刚刚加入了,所以声誉太低了),但是关于你的"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))适用于Tama和IA中的其他城市。不过要当心,像Des Moines这样的地名是不会起作用的,因为URL中不允许有空格-你必须注意这一点。(接口示例建议_ for spaces http://www.wunderground.com/weather/api/d/docs?MR=1)。祝好运!
发布于 2017-03-09 11:41:49
嘿,不知道你是不是还在这上面,但这是我的looking项目,它应该有你正在寻找的https://github.com/Oso9817/weather_texts
发布于 2016-01-25 01:07:30
如果有str.input,则需要使用str(位置)。现在,如果您进入python repl并输入str,您会发现它是一个保留关键字。您希望使用从用户输入而不是str对象获得的变量location。
https://stackoverflow.com/questions/34978531
复制相似问题