How is your data stored? (site was not loading for me). test = 'blah = [1,2,3,4,5]' >>> var,val = test.split('=') >>> print var,val blah [1,2,3,4,5] >>> val = val.strip('[] ') >>> print val 1,2,3,4,5 >>> vals = [int(x) for x in val.split(',')] >>> print vals [1, 2, 3, 4, 5]
More sophisiticated situations (like nested lists) may require something like pyparsing. from pyparsing import Suppress, Regex, delimitedList, Forward, QuotedString stringValue = QuotedString('"', '\\', multiline=True) intValue = Regex(r'[+-]?0|([1-9][0-9]*)') intValue.setParseAction(lambda s,l,toks: int(toks[0])) floatValue = Regex(r'[+-]?[0-9]+\.[0-9]+([eE][+-]?[0-9]+)?') floatValue.setParseAction(lambda s,l,toks: ('real', float(toks[0]))) constantValue = stringValue ^ intValue ^ floatValue arrayInitializer = Forward() arrayInitializer << (Suppress("[") + delimitedList(constantValue ^ arrayInitializer) \ + Suppress("]")) arrayInitializer.setParseAction(lambda s,l,toks: toks.asList()) test_data = '["a", 1, 5.6, ["b","c",6, 10.0e-19]]' print arrayInitializer.parseString(test_data) results in: ['a', 1, ('real', 5.5999999999999996), 'b', 'c', 6, ('real', 1.0000000000000001e-18)] -Chris On Wed, Aug 09, 2006 at 10:23:49AM -0400, Brendon Towle wrote: > Slawomir Nowaczyk noted: > > #> Heck, whenever *is* it OK to use eval() then? > eval is like optimisation. There are two rules: > Rule 1: Do not use it. > Rule 2 (for experts only): Do not use it (yet). > > So, that brings up a question I have. I have some code that goes out to a > website, grabs stock data, and sends out some reports based on the data. > Turns out that the website in question stores its data in the format of a > Python list ([1]http://quotes.nasdaq.com/quote.dll?page=nasdaq100, search > the source for "var table_body"). So, the part of my code that extracts > the data looks something like this: > START_MARKER = 'var table_body = ' > END_MARKER = '];' > def extractStockData(data): > pos1 = data.find(START_MARKER) > pos2 = data.find(END_MARKER, pos1) > return eval(data[pos1+len(START_MARKER):END_MARKER]) > (I may have an off-by-one error in there somewhere -- this is from memory, > and the code actually works.) > My question is: what's the safe way to do this? > B. > -- > Brendon Towle, PhD > Cognitive Scientist > +1-412-690-2442x127 > Carnegie Learning, Inc. > The Cognitive Tutor Company ? > Helping over 375,000 students in 1000 school districts succeed in math. > > References > > Visible links > 1. http://quotes.nasdaq.com/quote.dll?page=nasdaq100 > -- > http://mail.python.org/mailman/listinfo/python-list
-- http://mail.python.org/mailman/listinfo/python-list