def look_at_something(tokens): d = {'action': 'look'} target = tokens[0][1] if target['target'] == "around": target['target'] = "CURRENT_ROOM" d.update(target) return d def move_somewhere(tokens): ele = tokens[0] if isinstance(ele, dict): ele = [ ele, ] d = {'action': 'move'} d.update(ele[-1]) return d take_command.setParseAction(take_something) wear_command.setParseAction(wear_something) look_command.setParseAction(look_at_something) move_command.setParseAction(move_somewhere) command = MatchFirst([take_command, wear_command, look_command, move_command]) print(command.parseString("go n")) print(command.parseString("n")) # elementRef.setParseAction( computeElementWeight ) print("OK??")
"""Parse the TSV template format with PyParsing then make a new parser.""" from pyparsing import Group, MatchFirst, Optional, Suppress, delimitedList, nestedExpr, pyparsing_common as ppc from table_validator import parse_tsv keyword = ppc.identifier + Suppress('=') + ppc.identifier te_keywords = nestedExpr(content=delimitedList(keyword)) te_content = ppc.identifier + Optional(te_keywords) template_command = nestedExpr(opener='{', closer='}', content=te_content) cell = MatchFirst([ Group(template_command)('command'), Group(template_command)('command') + ppc.identifier('text'), ppc.identifier('text'), ]) if __name__ == '__main__': with open('../../tests/repeat_template.tsv') as file: t = [ [ cell.parseString(col) for col in row ] for row in parse_tsv(file) ] for i, row in enumerate(t): for j, col in enumerate(row): print(i, j, col.asList())