pyparsing和换行符 [英] pyparsing and line breaks

查看:109
本文介绍了pyparsing和换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚从pyparsing开始,但是在换行时遇到了问题.

I just started with pyparsing and I have problems with line breaks.

我的语法是:

from pyparsing import *

newline = LineEnd () #Literal ('\n').leaveWhitespace ()
minus = Literal ('-')
plus = Literal ('+')
lparen = Literal ('(')
rparen = Literal (')')
ident = Word (alphas)
integer = Word (nums)

arith = Forward ()
parenthized = Group (lparen + arith + rparen)
atom = ident | integer | parenthized

factor = ZeroOrMore (minus | plus) + atom
arith << (ZeroOrMore (factor + (minus | plus) ) + factor)

statement = arith + newline
program = OneOrMore (statement)

现在,当我解析以下内容时:

Now when I parse the following:

print (program.parseString ('--1-(-a-3+n)\nx\n') )

结果符合预期:

['-', '-', '1', '-', ['(', '-', 'a', '-', '3', '+', 'n', ')'], '\n', 'x', '\n']

但是当第二行可以解析为第一行的尾部时,第一行\n被魔术掉了吗?

But when the second line can be parsed as tail of the first line, the first \n is magicked away?

代码:

print (program.parseString ('--1-(-a-3+n)\n-x\n') )

实际结果:

['-', '-', '1', '-', ['(', '-', 'a', '-', '3', '+', 'n', ')'], '-', 'x', '\n']

预期结果:

['-', '-', '1', '-', ['(', '-', 'a', '-', '3', '+', 'n', ')'], '\n', '-', 'x', '\n']

实际上,我不希望解析器自动加入语句.

Actually I don't want the parser to automatically join statements.

1.我在做什么错了?

2.我该如何解决?

3.

推荐答案

'\ n'通常被跳过为空白字符.如果希望'\ n'为有效,则必须调用setDefaultWhitespaceChars来将'\ n'删除为可跳过的空格(必须在定义任何pyparsing表达式之前执行此操作):

'\n' is normally skipped over as a whitespace character. If you want '\n' to be significant, then you have to call setDefaultWhitespaceChars to remove '\n' as skippable whitespace (you have to do this before defining any of your pyparsing expressions):

from pyparsing import *
ParserElement.setDefaultWhitespaceChars(' \t')

这篇关于pyparsing和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆