我最近重新編寫一些代碼來python3並在尋找一個乾淨的Python的解決方案,解碼由urllib.request.urlopen返回的字節被傳遞到csv.reader使用python3從urllib解碼字節,有沒有更好的方法?
我想出了以下內容:
import urllib.request
def fetch(symbol='IBM'):
kwargs = { 'symbol': symbol,
'start_month': '01',
'start_day': '01',
'start_year': '2002',
'end_month': '12',
'end_day': '31',
'end_year': '2012',
}
urlstring = 'http://ichart.finance.yahoo.com/table.csv?s={symbol}&a={start_month}&b={start_day}&c={start_year}&d={end_month}&e={end_day}&f={end_year}&g=d&ignore=.csv'.format(**kwargs)
data = [row for row in csv.reader(map(bytes.decode, urllib.request.urlopen(urlstring), ('iso-8859-1' for i in iter(lambda:0,1))))]
return data
我想知道是否有更好的解決方案?本質上,url正在返回一個csv文件,並且在Python 2.x中,我能夠使用urllib2並將urllib2.urlopen()的返回值傳遞給csv.reader()。但是,在Python 3.x中,我們現在返回字節,所以我將響應映射到了bytes.decode並將其傳回給csv.reader。但我很好奇,如果有更好的方法來做到這一點,或者我尋找最佳解決方案時錯過了一些東西?
什麼是適當的pythonic方式來處理這種情況下,返回的對象需要解碼之前,我們將其傳遞給另一個函數進行迭代?
編輯: Thanks Ignacio!
看着你給我的鏈接,我得到了以下解決方案:
data=[row for row in csv.reader(codecs.iterdecode(urllib.request.urlopen(urlstring),'iso-8859-1'))]
這看起來清爽多了!