python - 正确使用SkipTo

标签 python pyparsing

我过去使用过 pyparsing,但仅用于小任务,这次我尝试将它用于更复杂的任务。

我试图跳过 VHDL 架构 block ,如下所示

architecture Behav of Counter is
  ...many statements I'm not interested in at this point...
end architecture;

这是我尝试过的:

import pyparsing as pp
pp_identifier = pp.Regex(r'([a-zA-Z_][\w]*)')('identifier')
def Keyword(matchString):
    'VHDL keywords are caseless and consist only of alphas'
    return pp.Keyword(matchString, identChars=pp.alphas, caseless=True)

pp_architecture = (
    Keyword('architecture')
    + pp_identifier
    + Keyword('of').suppress()
    + pp_identifier
    + Keyword('is').suppress()
    + Keyword('end')
    + Keyword('architecture')
    )

print(pp_architecture.parseString('''
architecture beh of sram is end architecture
''', parseAll=True))

# this works as I expected, it prints
# ['architecture', 'beh', 'sram', 'end', 'architecture']

但是在将 pp_architecture 更改为使用 SkipTo 后,它失败了:

pp_architecture = (
    Keyword('architecture')
    + pp_identifier
    + Keyword('of').suppress()
    + pp_identifier
    + Keyword('is').suppress()
    + pp.SkipTo(Keyword('end') + Keyword('architecture'))
    )

print(pp_architecture.parseString('''
architecture beh of sram is end architecture
''', parseAll=True))
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "C:\Python27\lib\site-packages\pyparsing.py", line 1125, in parseString
    raise exc
pyparsing.ParseException: Expected end of text (at char 29), (line:2, col:29)

我还尝试在 isend 之间添加其他文本(我希望被跳过),以确保这不是“空跳过”的问题,但这也没有帮助。

我做错了什么?

最佳答案

SkipTo 跳到匹配的文本,但默认情况下解析该文本。因此,您将解析位置推进到“结束架构”,但实际上并没有解析它。

您可以:

  1. SkipTo 表达式后添加 Keyword('end') + Keyword('architecture'),或者
  2. SkipTo 表达式的构造函数中传递 include=True,告诉它跳到解析给定的字符串。

关于python - 正确使用SkipTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712042/

相关文章:

python - SQLAlchemy 删除相关元素取决于标志

python请求模块和连接重用

python - 使用 pyparsing 从字符串中获取所有数字作为列表

python - Pyparsing 使用 Forward 解析递归表达式

python - `pip install foo-package==1.0.0` 今天下载的代码是否与昨天不同

python - 将 celery 与现有的 MySQL 表一起使用而不是 broker ,这可能吗?

python - OSError : [Errno 7] Argument list too long on ubuntu, python 使用 popen 调用 bitcoind-cli

python - pyparsing 用分号代替逗号解析csv文件

python - Pyparsing:将 infixnotation 与 setResultsName 结合起来

python - pyparsing部分匹配或递归限制命中