如何从C头文件中自动删除某些预处理器指令和注释?

2024-10-03 02:42:59 发布

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

从一个位于/* */和{}以及相应的{}之间的文件中删除所有文本的好方法是什么?我想把这些部分从C头中去掉。这是我目前掌握的代码:

For line in file:

    if def0Encountered == 0:  
        if Line.strip().startswith('#if 0') == True:  
            Def0StartsAt = Line.find('#if 0')  
            def0Encountered = 1  
            if Line.find('#endif')!= -1:  
                def0Encountered = 0  
                Def0EndsAt = Line.find('endif')  
                Line = Line[0:Def0StartsAt] + Line[Def0EndsAt + 2 : ]  
                List = Line.split()  

Tags: 文件方法代码in文本forifline
2条回答

您可以使用正则表达式将文件中不需要的部分替换为空字符串(注意,这是非常基本的,它不适用于嵌套宏):

#!/usr/bin/env python

import re

# uncomment/comment for test with a real file ...
# header = open('mycfile.c', 'r').read()
header = """

#if 0
    whatever(necessary)
    and maybe more

#endif

/* 
 * This is an original style comment
 *
 */

int main (int argc, char const *argv[])
{
    /* code */
    return 0;
}

"""

p_macro = re.compile("#if.*?#endif", re.DOTALL)
p_comment = re.compile("/\*.*?\*/", re.DOTALL)

# Example ...
# print re.sub(p_macro, '', header)
# print re.sub(p_comment, '', header)

不确定这个奇怪的代码应该做什么,但是可以直接逐行遍历文件。使用两个标志检查是否在注释或和if块内。根据字符串比较切换标志。根据这两个标志的值,您要么输出当前行,要么忽略它。。。。在

相关问题 更多 >