Created
June 13, 2014 17:19
-
-
Save iorlas/f8a60fa97c55493fd7aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pyparsing import * | |
class Percent(float): | |
def __str__(self): | |
return super(Percent, self).__str__() + '%' | |
def __repr__(self): | |
return super(Percent, self).__repr__() + '%' | |
number = Word(nums + '.-').setParseAction(lambda s, l, t: float(t[0])) | |
percent = Word(nums + '.-').setParseAction(lambda s, l, t: Percent(t[0])) + Suppress('%') | |
operand = percent | number | |
expr = infixNotation(operand, [ | |
(oneOf('* /'), 2, opAssoc.LEFT), | |
(oneOf('>'), 2, opAssoc.LEFT), | |
(oneOf('<'), 2, opAssoc.LEFT), | |
(oneOf('<='), 2, opAssoc.LEFT), | |
(oneOf('>='), 2, opAssoc.LEFT), | |
(oneOf('+ -'), 2, opAssoc.LEFT), | |
(oneOf('AND and && &'), 2, opAssoc.LEFT), | |
(oneOf('OR or || |'), 2, opAssoc.LEFT), | |
]) | |
nyamo = OneOrMore(Group(expr + Optional(Suppress("if") + expr) + Suppress(LineEnd()))) | |
code = """ | |
(10 + 5%) * 3 / 5 if 10 > 4 < 10 | |
10 + 1% if 10 > 1 | |
10 + 3% if 10 > 0 | |
10 + 100% * 10 | |
""" | |
r = nyamo.parseString(code) | |
print r | |
for i in r: | |
print i, len(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment