문제

Yet another what is wrong with this grammar question:

I am playing with pyPEG2 by Volker Birk and I am stuck with a very trivial case:

from pypeg2 import *

text = 'f(x)'
grammar = name, '(' , word,')'
print parse(text, grammar)

The exception I am getting looks like:

Traceback (most recent call last): File "test.py", line 5, in print parse(text, grammar) File "/home/yy/dev/python/len/len/lang/pypeg2/init.py", line 539, in parse t, r = parser.parse(text, thing) File "/home/yy/dev/python/len/len/lang/pypeg2/init.py", line 644, in parse t, r = self._parse(t, thing, pos) File "/home/yy/dev/python/len/len/lang/pypeg2/init.py", line 814, in _parse t2, r = self._parse(t, e, pos) File "/home/yy/dev/python/len/len/lang/pypeg2/init.py", line 962, in _parse raise GrammarTypeError("in grammar: " + repr(thing)) pypeg2.GrammarTypeError: in grammar: '('

parse() fails on parsing opening round bracket which supposed to be a Symbol(). Surely I am missing something obvious, but what?

도움이 되었습니까?

해결책

I updated the documentation because of people having such problems. pyPEG2 is written for Python 3. That means, it uses Unicode strings all the way. For Python 2.7, this would require strings of the form i.e. u'f(x)'. Because I don't want to have the documentation twice, I'm recommending from __future__ import unicode_literals, print_function

VB.

다른 팁

from __future__ import unicode_literals, print_function
from pypeg2 import *

text = 'f(x)'
grammar = name(), '(' , attr('Param',word),')'
print(parse(text, grammar))

outputs

[Attribute(name=u'name', thing=Symbol(u'f'), subtype=None), Attribute(name=u'Param', thing=u'x', subtype=None)]

Why? RTFM!!

Caveat: pyPEG 2.x is written for Python 3. You can use it with Python 2.7 with the following import (you don't need that for Python 3)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top