我不知道如何按原样解析纯文本(也包括空白),并且仍然能够匹配文本中的特殊结构。假设你有一根像
some plain text
specialStructure
plain text again
我要实现的是一个解析器 在
^{pr2}$我的第一次尝试是 在
^{3}$即使这给了我在这个例子中想要的,问题是如果纯文本有一些换行符、制表符或其他类型的空白,最后我只能得到空格键分隔的单词。。。在
在找到一个特殊的结构或输入的结尾之前,我如何匹配纯文本呢?在
更新
我发现的一个部分解决方案是使用skipot类: 在
import pyparsing as pp
struct = pp.Regex(r'specialStructure')
txt = pp.SkipTo( struct ) | pp.SkipTo( pp.StringEnd(), include=True )
grammar = pp.ZeroOrMore( struct | txt )
result = grammar.parseString(s)
这里的问题在于嵌套结构。假设有一个更复杂的字符串要解析,如:
s = """
some plain text
nestedStructureBegin
here we are inside a nested structure
nestedStructureBegin
bla bla
nestedStructureEnd
nestedStructureEnd
some bla bla again.
"""
import pyparsing as pp
grammar = pp.Forward()
begin = pp.Regex(r'nestedStructureBegin').suppress()
end = pp.Regex(r'nestedStructureEnd').suppress()
struct = begin + pp.Group(grammar) + end
keyword = begin | end
txt = pp.SkipTo( keyword ) | pp.SkipTo( pp.StringEnd(), include=True )
grammar << pp.ZeroOrMore( struct | txt )
for parser in [struct, txt]:
parser.addParseAction(lambda toks: print(toks))
result = grammar.parseString(s)
我认为问题在于pp.StringEnd公司这在嵌套结构中不匹配,但我不确定这有什么问题。。。有什么建议吗?在
我已经找到了一个即使在嵌套结构中也能很好工作的解决方案。其思想是逐字符解析输入,然后使用
pp.Combine
重建原始的纯文本输入。 在相关问题 更多 >
编程相关推荐