pyparsing中的注释

2024-09-30 01:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的语法很简单。基本上它是由块组成的,每个块 以&和一些名称开头,并向下延伸到下一个或结尾 文件的。此外,还有两种注释:一行注释, 从*到行尾,以及包含在/* */中的C样式注释。 注释也可以在块内。我目前为止的尝试:

#!/usr/bin/env python
from pyparsing import *

NL = Suppress( LineEnd() )
restOfLineNL = restOfLine + NL

LineComment = Literal('*') + restOfLineNL
BlockComment = nestedExpr('/*', '*/')
Comment = BlockComment | LineComment

ModuleName = LineStart() + Word( '&', alphanums + '_', min=2 ) + NL
Module = ModuleName + SkipTo( StringEnd() | ModuleName, include=False)
Grammar = ZeroOrMore( Module )
Grammar.ignore(Comment)

result = Grammar.parseString('''
&keyword1

*comment

&keyword2
arbitrary lines
* with comments interspersed
possibly empty

/*
&keyword3
c-style comments
are allowed too
*/

&keyword4

''', parseAll=False)

for line in result:
  print('|'+line.rstrip()+'|')

这将导致:

^{pr2}$

有几个问题:

  1. 不会删除关键字2内的注释。在
  2. 不会删除关键字3周围的C样式注释。在

有什么办法解决这个问题吗?或者用别的python包来解析这种文件?在


Tags: 文件falsenllinecomment样式关键字result

热门问题