Pyparsing:如何实现C风格注释的特殊处理?
我想利用 cStyleComment 变量,但我想专门处理它们,而不是仅仅忽略这些注释。有没有什么方法可以让 pyparsing 在将其识别为注释的输入片段上调用我的处理程序,然后将其丢弃?
我正在处理一些 C 代码,其中在注释中包含一些“特殊”指令。
I want to take advantage of the cStyleComment variable, but rather than just ignoring these comments I want to process them specially. Is there any way to make pyparsing call my handler on the piece of input, which it recognizes as a comment, before it's going to be thrown away?
I'm processing some C code, which contain some "special" directives inside comments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
pyparsing 中定义的任何
xxxStyleComment
表达式中没有任何固有的内容导致它们被忽略。它们的存在是为了方便,特别是因为某些注释格式很容易出错。它们不会被忽略,除非您在较大的语法上调用ignore
方法,如下所示:(其中
cHeaderParser
可能是您编写的用于读取 .h 文件以提取的内容例如,API 信息。)并且内置了对处理程序的 pyparsing 回调,只需使用
cStyleComment.setParseAction(commentHandler)
即可。 Pyparsing 可以处理具有以下任何签名的解析操作:如果您的 commentHandler 返回一个字符串或字符串列表,或者一个新的 ParseResults,这些将用于替换输入标记 - 如果它返回 None,或省略 return 语句,则使用 tokens 对象。您还可以就地修改标记对象(例如添加新的结果名称)。
因此,您可以编写类似这样的内容,将您的注释大写:(
甚至可以编写像这样简单的解析操作
cStyleComment.setParseAction(lambda t:t[0].upper())
)编写这样的转换解析操作,可能会使用
transformString
而不是parseString
,这将打印原始源代码,但所有注释都将大写。
There is nothing inherent in any of the
xxxStyleComment
expressions that are defined in pyparsing that causes them to be ignored. They are there as a convenience, especially since some comment formats are easy to get wrong. They don't get ignored unless you call theignore
method on your larger grammar, as in:(where
cHeaderParser
might be something you wrote to read through .h files to extract API information, for instance.)And having pyparsing callback to a handler is built-in, just use
cStyleComment.setParseAction(commentHandler)
. Pyparsing can handle parse actions with any of these signatures:If your commentHandler returns a string or list of strings, or a new ParseResults, these will be used to replace the input tokens - if it returns None, or omits the return statement, then the tokens object is used. You can also modify the tokens object in place (such as adding new results names).
So you could write something like this that would uppercase your comments:
(a parse action as simple as this could even be written
cStyleComment.setParseAction(lambda t:t[0].upper())
)When writing a transforming parse action like this, one would likely use
transformString
rather thenparseString
,This will print the original source, but all of the comments will be uppercased.