我一直在努力尝试从旧版本的Python转换一些代码。我只是试图从wunderground运行api查找,我无法通过python中的错误。这是错误: f = urllib.request.urlopen(fileName) AttributeError:'module'对象没有属性'request'
代码非常简单,我知道我错过了一些简单的东西,感谢您的帮助。
import urllib
import json
key = "xxxxxxxxxxxxxxxxx"
zip = input('For which ZIP code would you like to see the weather? ')
fileName = "http://api.wunderground.com/api/" + key + "/geolookup/conditions/q/PA/" + zip + ".json"
f = urllib.request.urlopen(fileName)
json_string = f.read()
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)")
close()
答案 0 :(得分:3)
有时导入包(例如numpy
)会自动将子模块(例如numpy.linalg
)导入其命名空间。但urllib
的情况并非如此。所以你需要使用
import urllib.request
而不是
import urllib
以访问urllib.request
模块。或者,您可以使用
import urllib.request as request
以request
的身份访问模块。
查看examples in the docs是避免将来出现此类问题的好方法。
由于f.read()
会返回bytes
个对象,json.loads
需要str
,因此您还需要对字节进行解码。特定编码取决于服务器决定发送给您的内容;在这种情况下,字节是utf-8
编码的。所以使用
json_string = f.read().decode('utf-8')
parsed_json = json.loads(json_string)
解码字节。
最后一行有一个小错字。使用
print ("Current temperature in %s is: %s" % (location, temp_f))
使用值"Current temperature in %s is: %s"
插入字符串(location, temp_f)
。请注意引号的位置。
提示:由于zip
是内置函数,因此最好不要命名
变量zip
,因为这会改变zip
的通常含义,使其变得更难
对于其他人,也许是未来 - 您要了解您的代码。修复很简单:将zip
更改为其他内容,例如zip_code
。
import urllib.request as request
import json
key = ...
zip_code = input('For which ZIP code would you like to see the weather? ')
fileName = "http://api.wunderground.com/api/" + key + "/geolookup/conditions/q/PA/" + zip_code + ".json"
f = request.urlopen(fileName)
json_string = f.read().decode('utf-8')
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))
答案 1 :(得分:1)
我建议使用requests library Python HTTP for Humans.,下面的代码适用于python2或3:
import requests
key = "xxxxxxxxxxx"
# don't shadow builtin zip function
zip_code = input('For which ZIP code would you like to see the weather? ')
fileName = "http://api.wunderground.com/api/{}/geolookup/conditions/q/PA/{}.json".format(key, zip_code)
parsed_json = requests.get(fileName).json()
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
# pass actual variables and use str.format
print ("Current temperature in {} is: {}%f".format(location, temp_f))
获取json只是requests.get(fileName).json()
,使用str.format
是首选方法,我发现不容易出错,与旧版printf
相比,它的功能更丰富样式格式。
你可以看到它在2和3下都可以运行样本:
:~$ python3 weat.py
For which ZIP code would you like to see the weather? 12212
Current temperature in Albany is: 68.9%f
:~$ python2 weat.py
For which ZIP code would you like to see the weather? 12212
Current temperature in Albany is: 68.9%f