Created
February 3, 2018 15:50
-
-
Save k5trismegistus/6ea61a887cdd068ffb8ed18de81fb3b4 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
import sys | |
from lark import Lark, Transformer | |
class Calculator(Transformer): | |
def addition(self, items): | |
return items[0] + items[1] | |
def substraction(self, items): | |
return items[0] - items[1] | |
def multiplication(self, items): | |
return items[0] * items[1] | |
def divisiton(self, items): | |
return items[0] / items[1] | |
def fact(self, items): | |
return float(items[0]) | |
def number(self, items): | |
return float(items[0]) | |
if __name__ == '__main__': | |
expression = ' '.join(sys.argv[1:]) | |
rule = open('grammer.txt').read() | |
calc_parser = Lark(rule, start='expr', parser='lalr') | |
tree = calc_parser.parse(expression) | |
print(tree.pretty()) | |
result = Calculator().transform(tree) | |
print(f'計算結果: {result}') |
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
?expr: term | |
| addition | |
| substraction | |
addition: expr "+" term | |
substraction: expr "-" term | |
?term: fact | |
| multiplication | |
| division | |
multiplication: term "*" fact | |
division: term "/" fact | |
?fact: number | |
| priority | |
?priority: "(" expr ")" | |
number: SIGNED_NUMBER | |
%import common.SIGNED_NUMBER | |
%import common.WS | |
%ignore WS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment