如何使用 pyparsing Group 和 SkipTo 进行文件解析? [英] How to use pyparsing Group with SkipTo for a file parsing?

查看:33
本文介绍了如何使用 pyparsing Group 和 SkipTo 进行文件解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将pyparsing SkipTo与其他解析器一起使用时,文件解析似乎挂起.

When I used pyparsing SkipTo together with other parser, the file parsing seems hang.

unexpected = pp.SkipTo(pp.LineEnd())('unexpected*')
rules = pp.Group(predefined_parser) | unexpected

parser = pp.Dict(pp.OneOrMore(rules)
parser.ignore('*' + pp.restOfLine)
parser.parseFile(filename, True)

我打开了 setDebug,这是调试信息.任何见解都非常感谢.

I turned on setDebug, here's the debug message. Any insights is highly appreciated.

Match Dict:([{Group:({Combine:({"something" W:(_) Combine:({W:(ABCD...) [W:(0123...)]}) W:(_) {"sth1" | "sth2"}}) Suppress:("=") W:(0123...)}) | SkipTo:(LineEnd)}]...) at loc 0(1,1)

我改成下面这样后,抛出了AttributeError.

After I changed to the following, AttributeError thrown.

unexpected = pp.SkipTo(pp.LineEnd(), include=True)('unexpected*')

这是 AttributeError 消息.

Here's the AttributeError message.

File "/nfs/pdx/disks/icf_gwa_002/ylim13/anaconda2/lib/python2.7/site-packages/pyparsing.py", line 1599, in parseFile
  return self.parseString(file_contents, parseAll)
File "/nfs/pdx/disks/icf_gwa_002/ylim13/anaconda2/lib/python2.7/site-packages/pyparsing.py", line 1078, in _parseNoCache
  tokens = self.postParse( instring, loc, tokens )
File "/nfs/pdx/disks/icf_gwa_002/ylim13/anaconda2/lib/python2.7/site-packages/pyparsing.py", line 3249, in postParse
  dictvalue = tok.copy() #ParseResults(i)
AttributeError: 'str' object has no attribute 'copy'

推荐答案

简短回答 - 更改:

    | pp.SkipTo(pp.LineEnd(), include=True)

到:

    | pp.SkipTo(pp.LineEnd(), include=True).suppress()

当 this 传递给 Dict 时,它会看到由 SkipTo 创建的两个值,因此假设它是键值对的解析结果,要添加到累积 dict 中.通过抑制这个结果,Dict 得到一个空字符串,它知道忽略它.

When this is passed to Dict, it sees the two values created by SkipTo, so assumes it is the parsed results from a key-value pair, to be added into the cumulative dict. By suppressing this result, Dict gets an empty string, which it knows to ignore.

这篇关于如何使用 pyparsing Group 和 SkipTo 进行文件解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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