gpt4 book ai didi

python - Wunderground api 搜索栏

转载 作者:行者123 更新时间:2023-12-01 04:10:47 24 4
gpt4 key购买 nike

我目前正在编写一个搜索天气的程序。我正在尝试创建一个选项,您可以在其中搜索您的位置,但它似乎不起作用。

  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()

我不断收到此错误

最佳答案

还不能发表评论(因为我刚刚加入 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))

适用于多摩和爱荷华州的其他城市。但请注意,像 Des Moines 这样的地名不起作用,因为 URL 中不允许有空格 - 您必须注意这一点。 (API 的示例建议用 _ 表示空格 http://www.wunderground.com/weather/api/d/docs?MR=1 )。祝你好运!

关于python - Wunderground api 搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34978531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com