2015-07-04 42 views
3

我一直在努力嘗試從舊版本的Python轉換一些代碼。我只是試圖從wunderground運行api查找,並且無法通過python查看我的錯誤。以下是錯誤: F = urllib.request.urlopen(文件名) AttributeError的:「模塊」對象有沒有屬性「要求」Python 3.3.2 - 試圖從wunderground中讀取url

的代碼是相當直接的,我知道我的「M簡單的東西,謝謝任何幫助。

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

回答

3

有時導入包(如numpy)自動導入子模塊(如numpy.linalg)到它的命名空間。但是,這並不是urllib的情況。所以,你需要使用

import urllib.request 

代替

import urllib 

爲了訪問urllib.request模塊。或者,你可以爲了訪問模塊request使用

import urllib.request as 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)) 

與價值(location, temp_f)插值字符串"Current temperature in %s is: %s"。請注意引號的位置。


提示:由於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)) 
+0

感謝,這也幫我找到了我的錯誤,當我使用閒置。 –

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 
+0

非常感謝,只是改成了requests.get()。json(),效果很好。 –

+0

沒有問題,請求爲你做了很多艱苦的工作。 –