2016-04-10 104 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