我有以下程序從網站中取消數據。我想通過使用帶有收益率的發電機而不是多次調用generate_url
和call_me
來改進以下代碼。這種exersise的目的是正確理解yield
和它可以使用的上下文。在python中使用`yield`關鍵字的上下文
import requests
import shutil
start_date='03-03-1997'
end_date='10-04-2015'
yf_base_url ='http://real-chart.finance.yahoo.com/table.csv?s=%5E'
index_list = ['BSESN','NSEI']
def generate_url(index, start_date, end_date):
s_day = start_date.split('-')[0]
s_month = start_date.split('-')[1]
s_year = start_date.split('-')[2]
e_day = end_date.split('-')[0]
e_month = end_date.split('-')[1]
e_year = end_date.split('-')[2]
if (index == 'BSESN') or (index == 'NSEI'):
url = yf_base_url + index + '&a={}&b={}&c={}&d={}&e={}&f={}'.format(s_day,s_month,s_year,e_day,e_month,e_year)
return url
def callme(url,index):
print('URL {}'.format(url))
r = requests.get(url, verify=False,stream=True)
if r.status_code!=200:
print "Failure!!"
exit()
else:
r.raw.decode_content = True
with open(index + "file.csv", 'wb') as f:
shutil.copyfileobj(r.raw, f)
print "Success"
if __name__ == '__main__':
url = generate_url(index_list[0],start_date,end_date)
callme(url,index_list[0])
url = generate_url(index_list[1],start_date,end_date)
callme(url,index_list[1])
那麼......問題是什麼? – user2357112
@ user2357112 - 關於如何在此上下文中使用yield。 – liv2hak
可能重複[在Python中yield關鍵字有什麼作用?](http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python) – ppperry