【问题标题】:Wunderground api search barWunderground api 搜索栏
【发布时间】:2016-01-24 16:48:20
【问题描述】:

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

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

我不断收到此错误

【问题讨论】:

    标签: python json api


    【解决方案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))
    

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

    【讨论】:

    • 我已经尝试过了,但是它返回一个错误 NameError: name 'response' is not defined
    • 那是因为你没有将你的 urlopen(url) 分配给任何东西。提示:request = urlopen(url)
    • 我的 urlopen 没有错误。我有这个错误 json_string = response.read().decode('utf8') NameError: name 'response' is not defined
    • 我知道。因为您的程序不知道“响应”是什么。你还没有定义它。我认为这是您从 urlopen 得到的响应。现在,你打开 url 并把结果扔掉。
    • 我尝试过定义“响应”。请看我的编辑2。谢谢
    【解决方案2】:

    嘿,不确定你是否仍然坚持这一点,但这是我的奇妙项目,应该有你正在寻找的东西 https://github.com/Oso9817/weather_texts

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 好的,谢谢,我刚刚尝试了您的建议,它似乎解决了问题,但是我收到另一个问题,说“urllib”未定义。
      猜你喜欢
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 2015-05-03
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多