在编写可以与 expression.transformString() 一起使用的单个解析器表达式时,我试了几次,但在解析时我很难区分嵌套和未嵌套的 []。最后,我不得不在 transformString 中打开循环并显式迭代 scanString 生成器。
为了解决是否应该根据原始问题包含 [some] 的问题,我通过在末尾添加更多“未嵌套”文本进行了探索,使用以下字符串:
src = """[This] is some text with [some [blocks that are
nested [in a [variety] of ways]] in various places]"""
我的第一个解析器遵循原始问题的引导,并拒绝任何具有 any 嵌套的括号表达式。我的第二遍获取任何括号表达式的顶级标记,并将它们返回到括号中 - 我不太喜欢这个解决方案,因为我们丢失了“一些”和“在各个地方”不连续的信息。所以我最后一次通过,不得不对nestedExpr 的默认行为稍作更改。请看下面的代码:
from pyparsing import nestedExpr, ParseResults, CharsNotIn
# 1. scan the source string for nested [] exprs, and take only those that
# do not themselves contain [] exprs
out = []
last = 0
for tokens,start,end in nestedExpr("[","]").scanString(src):
out.append(src[last:start])
if not any(isinstance(tok,ParseResults) for tok in tokens[0]):
out.append(src[start:end])
last = end
out.append(src[last:])
print "".join(out)
# 2. scan the source string for nested [] exprs, and take only the toplevel
# tokens from each
out = []
last = 0
for t,s,e in nestedExpr("[","]").scanString(src):
out.append(src[last:s])
topLevel = [tok for tok in t[0] if not isinstance(tok,ParseResults)]
out.append('['+" ".join(topLevel)+']')
last = e
out.append(src[last:])
print "".join(out)
# 3. scan the source string for nested [] exprs, and take only the toplevel
# tokens from each, keeping each group separate
out = []
last = 0
for t,s,e in nestedExpr("[","]", CharsNotIn('[]')).scanString(src):
out.append(src[last:s])
for tok in t[0]:
if isinstance(tok,ParseResults): continue
out.append('['+tok.strip()+']')
last = e
out.append(src[last:])
print "".join(out)
给予:
[This] is some text with
[This] is some text with [some in various places]
[This] is some text with [some][in various places]
我希望其中之一接近 OP 的问题。但如果不出意外,我还得进一步探索 nestedExpr 的行为。