2016-04-10 100 views
0
def getQuotesYahoo(): 

    tickerStr = "GOOGL+AMZN" 
    yahoo_url ="http://finance.yahoo.com/d/quotes.csv?s=%s&f=saohgb3t1" % (tickerStr) 
    retQuotes = {} 

    data = urllib2.urlopen(yahoo_url).readlines() 

    for d in data: 
     p = d.strip().split(',') 
     stkInfo = {} 
     stkInfo['lastTime'] = p[6] 
     stkInfo['last'] = p[1] 
     stkInfo['open'] = p[2] 
     stkInfo['high'] = p[3] 
     stkInfo['low'] = p[4] 
     stkInfo['bid'] = p[5] 
     tic = p[0] 
     print stkInfo 
     retQuotes[tic] = stkInfo 

    print retQuotes['GOOGL']['last'] 

此代碼在KeyError上失敗,未使用字符串鍵填充字典。我基本上有相同的代碼爲googlefiance工作。Python失敗,發生密鑰錯誤

KeyError: 'GOOGL'

retQuotes:

{'"AMZN"': {'last': '594.60', 'bid': 'N/A', 'high': '597.86', 'low': '589.00', 'lastTime': '"4:00pm"', 'open': '594.32'}, '"GOOGL"': {'last': '759.98', 'bid': 'N/A', 'high': '767.13', 'low': '755.77', 'lastTime': '"4:00pm"', 'open': '765.87'}}

+3

谷歌的股票代碼不是'GOOGL',它是'GOOG' – n1c9

+1

'retQuotes'中的結果是什麼?打印變量可能會有所幫助。 –

+0

看起來像股票是在結構中。 – user3763220

回答

0

它似乎是字典中的關鍵是'GOOGL''所以在雙引號中有雙引號。 (整個字符串實際上是「GOOGL」),所以你需要將它稱爲:

retQuotes['"GOOGL"']['last'] 

雖然它看起來像(與N/A除外)都從股市中的數據將是有效的蟒蛇文字,這意味着你可以使用ast.literal_eval分析數據作爲一個元組:

import ast 
field_names = ('last','open','high','low','bid','lastTime') 
for d in data: 
    d = d.replace("N/A","None") 
    fields = ast.literal_eval("(%s)"%d) #add round brackets to indicate the data is a tuple 
    stock = fields[0] 
    stkInfo = dict(zip(field_names,fields[1:])) 
    retQuotes[stock] = stkInfo 

d = d.replace("N/A","None") 
fields = ast.literal_eval("(%s)"%d) #add round brackets to indicate the data is a tuple 

您也可以通過使用zipdict構造縮短聲明

+0

我會認爲這也會更快。感謝您的幫助 – user3763220

+0

@ user3763220請知道[接受答案]的機制(http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 –

+0

謝謝你們。很有幫助。 – user3763220