我用 pyPEG2 创建了语法,用于解析以下语句:
A爱B,B恨A,A恨B,A爱D,B爱C
下面是我的代码:
import pypeg2 as pp
class Person(str):
grammar = pp.word
class Action(pp.Keyword):
grammar = pp.Enum(pp.K('loves'), pp.K('hates'))
class Separator(pp.Keyword):
grammar = pp.Enum(pp.K(','), pp.K('\n'), pp.K('but'), pp.K('and'), pp.K('while'))
relation = Person, Action, Person
class Relations(pp.Namespace):
grammar = relation, pp.maybe_some(Separator, relation)
但是,当我尝试执行以下操作时:
>>> love = pp.parse('A loves B but B hates A , B loves C, Relations)
我得到:
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
love = pp.parse('A loves B but B hates A , B loves C', Relations)
File "/home/michael/.local/lib/python3.5/site-packages/pypeg2/__init__.py", line 669, in parse
raise parser.last_error
File "<string>", line 1
es B but B hates A , B loves C
^
SyntaxError: expecting Separator
>>>
如果我更改此声明:
>>> love = pp.parse('A loves B but B hates A and B loves C', Relations)
没有错误,但由于某些原因错过了最后一个块:
>>> pp.compose(love)
'A loves B but B hates A'
那么我做错了什么,文档描述得很好,但无法真正找到我在那里犯的错误。
希望有人可以帮助解决这个问题。提前致谢!!!