python - Handling parsed variables stored in dictionary -
is there better, more pythonic way parse , set value variable (stored in var_dict dictionary) , value same?
the code below working, setting , getting parts complicated.
from pyparsing import word, nums, forward, zeroormore, alphas, alphanums, group, combine def test_grammar(): number = word(nums) itemlist = forward() items = (number | itemlist) itemlist << ('[' + items + zeroormore(',' + items) + ']') variable = word(alphas, alphanums+"_")("variable") data = itemlist("data") assignment = group(variable + '=' + data)("assignment") indexes = zeroormore('[' + number + ']')("index") query = combine(variable + indexes)("query") action = assignment | query return action var_dict = {} test_input1 = "nl = [1, [2, 3]]" test_input2 = "nl[1][1]" tokens1 = test_grammar().parsestring(test_input1) variable = tokens1['assignment']['variable'] data = ''.join(tokens1['assignment']['data']) var_dict[variable] = eval(data) print var_dict['nl'] tokens2 = test_grammar().parsestring(test_input2) variable = tokens2['query']['variable'] index = ''.join(tokens2['query']['index']) print eval("var_dict['" + variable + "']" + index)
produces desired:
[1, [2, 3]] 3
eval()
sign taking a, dangerous, shortcut instead of using language express solution. either out of laziness or lack of knowledge language. both eval()
calls can avoided.
the first used parse list of numbers can addressed pyparsings parse actions.
the second there avoid simple loop.
from pyparsing import ( word, nums, forward, zeroormore, alphas, alphanums, group, combine, suppress ) def test_grammar(): number = word(nums).setparseaction(lambda toks: int(toks[0])) itemlist = forward() items = number | itemlist itemlist << group( suppress('[') + items + zeroormore(suppress(',') + items) + suppress(']') ).setparseaction(lambda toks: list(toks)) variable = word(alphas, alphanums + '_')('variable') data = itemlist('data') assignment = group(variable + '=' + data)('assignment') indexes = zeroormore(suppress('[') + number + suppress(']'))('indexes') query = combine(variable + indexes)('query') action = assignment | query return action def main(): variables = dict() test_input_a = 'nl = [1, [2, 3]]' test_input_b = 'nl[1][1]' grammar = test_grammar() tokens = grammar.parsestring(test_input_a) data = tokens['assignment']['data'][0] variables[tokens['assignment']['variable']] = data print variables['nl'] tokens = grammar.parsestring(test_input_b) data = variables[tokens['query']['variable']] index in tokens['query']['indexes']: data = data[index] print data if __name__ == '__main__': main()
Comments
Post a Comment