Index: parse.py ================================================================== --- parse.py +++ parse.py @@ -1,6 +1,8 @@ #!/usr/bin/env python + +import tree from ply import lex, yacc class Note(): def __init__(self, value, duration=.25, octave=8): self.value = value @@ -35,21 +37,24 @@ "ACCIDENTAL", "REST", "OCTAVE", "CHORD_TYPE", "QUOTE", + "NODE", ) t_ignore = " |" #t_BASENOTE = r"[A-Ga-g]" - t_BASENOTE = r"I+V?|VI*|i+v?|vi*" +# t_BASENOTE = r"I+V?|VI*|i+v?|vi*" + t_BASENOTE = r"[A-Ga-g]" t_ACCIDENTAL = r"\^{1,2}|_{1,2}|=" t_REST = r"z" t_OCTAVE = r"'+|,+" t_CHORD_TYPE = r"m|7|m7|0|o|\+|mb5|sus|sus4|maj7|mmaj7|7sus4|dim|dim7|7b5|m7b5|6|b6|m6|mb6|46|maj9|9|add9|7b9|m9" t_QUOTE = '"' + t_NODE = r"([a-zA-Z0-9_-]+)" def t_NOTE_LENGTH(t): r"/?\d+" multiplier = float(t.value.strip("/")) if t.value.startswith("/"): @@ -76,17 +81,19 @@ def p_pitch_list(p): '''score : score note | score chord | score rest + | score node ''' p[0] = p[1] + [p[2]] def p_score(p): '''score : note | chord | rest + | node ''' p[0] = [p[1]] def p_note(p): @@ -145,13 +152,19 @@ | REST NOTE_LENGTH ''' p[0] = Rest() if len(p) > 2: p[0].duration = p[2] + + def node(p): + '''node: NODE + ''' + p[0] = tree.Tree(node.strip("(").strip(")")) + def p_error(p): raise Exception("Syntax error at '%s' of element type %s" % (p.value, p.type)) yacc.yacc() #print yacc.parse("GFG B'AB,, | g/2fg gab | GFG BAB | d2A AFD") return yacc.parse(score) ADDED tree.py Index: tree.py ================================================================== --- /dev/null +++ tree.py @@ -0,0 +1,32 @@ +import pdb + +class Tree(): + def __init__(self, name): + self.nodes = [] + self.name = name + + def traverse_depth_first(self): + all_nodes = [] + for node in self.nodes: + if isinstance(node, Node): + all_nodes.append(node) + elif isinstance(node, Tree): +# pdb.set_trace() + all_nodes.extend(node.traverse_depth_first()) + return all_nodes + + def __str__(self): + return str(self.__unicode__()) + def __unicode__(self): + return self.nodes + + +class Node(): + def __init__(self, parent, data): + self.parent = parent + self.data = data + + def __str__(self): + return str(self.__unicode__()) + def __unicode__(self): + return self.data