Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting symbols with Lark parsing

Tags:

python

parsing

I'm trying to parse a little pseudo-code I'm writing and having some trouble getting values for symbols. It parses successfully, but it won't return a value the same as it would with "regular" characters. Here's an example:

>>> from lark import Lark
>>> parser = Lark('operator: "<" | ">" | "=" | ">=" | "<=" | "!="', start="operator")
>>> parsed = parser.parse(">")
>>> parsed
Tree(operator, [])
>>> parsed.data
'operator'
>>> parsed.value
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Tree' object has no attribute 'value'

Why wouldn't there be a value? Is there another way to get the exact operator that was used?

like image 537
Mike Shultz Avatar asked Sep 01 '17 23:09

Mike Shultz


1 Answers

Author of Lark here. Mike's answer is accurate, but a better way to get the same result is by using the "!" prefix on the rule:

>>> from lark import Lark
>>> parser = Lark('!operator: "<" | ">" | "=" | ">=" | "<=" | "!="', start="operator")
>>> parser.parse(">")
Tree(operator, [Token(__MORETHAN, '>')])
like image 130
Erez Avatar answered Nov 14 '22 21:11

Erez