Skip to main content
 首页 » 编程设计

python之读取文件时避免使用 C 风格注释

2025年05月04日9zhwl

我正在使用 python 在函数中为 LOC 解析 C 文件。 我从函数定义的第一行开始并跳过所有行,直到我遇到第一个“{”。

问题是“{”也可以作为注释的一部分出现。我只想跳过评论中出现的所有“{”。

例如

100: int func( 
102:         int i, // some comment { .... 
103:         float f, 
104:         char c /* some comment here { ... 
105:                .... more comment */ 
106:         ) 
107:{ 

实现此目标的最佳 pythonic 方法是什么。

请您参考如下方法:

这是一个注释剥离器,它还应该包含引号字符串中的注释介绍符:

from pyparsing import cppStyleComment,dblQuotedString 
 
cppStyleComment.ignore(dblQuotedString) 
src = cppStyleComment.suppress().transformString(src) 
 
print src 

将您的原始片段作为 src,打印:

int func( 
             int i,  
             float f, 
             char c  
             ) 
    { 

您可以在内存中执行所有这些操作,因此您不必先创建无注释文件。