删除尾随空格

时间:2014-01-07 08:16:47

标签: python pyparsing

默认情况下,pyparsing只删除前导空格。

所以解析这个

'between ( 1, map(  v7 , 2  ) )'

给了我

['between', [['1'], ['map', [['v7 '], ['2  ']]]]]

而不是

['between', [['1'], ['map', [['v7'], ['2']]]]]

但如何使用pyparsing删除尾随空格?

代码是:

from pyparsing import Forward, Word, alphas, alphanums, nums, Literal, Group, delimitedList, Optional
lparen = Literal("(").suppress()
rparen = Literal(")").suppress()
name = Optional(Word(alphanums + '_ ', alphanums + '_ '))
functor = Word(alphas, alphanums)
integer  = Word( nums )
expression = Forward()
arg =  Group(expression) |name | integer 
args = delimitedList(arg)
expression << ((functor + lparen + args + rparen) | name)

print( expression.parseString("between ( 1, map(  v7 , 2  ) )"))
>>> ['between', ['1'], ['map', ['v7 '], ['2  ']]]

pyparsing。版本 ='2.0.1'和python3。

此时我在解析之前和之后使用其他外部函数来进行prapare和修复数据。

1 个答案:

答案 0 :(得分:0)

发布的代码有两次出现alphanums + '_ ' - 将它们更改为alphanums + '_'(删除空格)可以实现您所描述的内容。

from pyparsing import Forward, Word, alphas, alphanums, nums, Literal, Group, delimitedList, Optional

lparen = Literal("(").suppress()
rparen = Literal(")").suppress()
name = Optional(Word(alphanums + '_', alphanums + '_'))
functor = Word(alphas, alphanums)
integer = Word(nums)
expression = Forward()
arg = Group(expression) | name | integer 
args = delimitedList(arg)
expression << ((functor + lparen + args + rparen) | name)

print( expression.parseString("between ( 1, map(  v7 , 2  ) )"))

打印:

['between', ['1'], ['map', ['v7'], ['2']]]

我不确定你是否能够从评论中得出这个结论,但看起来这就是Paul McGuire所描述的内容。也就是说,pyparsing只在匹配的内容中包含空格,因为alphanums + '_ '在匹配的内容中包含了一个空格。