首页 > 解决方案 > 使用 Python 和正则表达式提取源代码中的 C++ 注释

问题描述

我正在从事一个项目,该项目要求我应该从 C++ 源代码中提取注释,而不管它位于何处。它可以是单行或多行注释。

我将以下内容作为txt文件中的数据输入,该文件已读入程序。

    /* this is a comment in C. This comment syntax is guaranteed to work
    on every compiler */ and
    // This is also a comment in C. but it might present portability
    challenges
    Fortran

    ! This is a comment in Fortran

    C++

    // This is single Line Comment in C++
    /* This is multi line comment.
    in C++
    */

我的任务是提取除注释标签之外的人类可读的注释部分,因此使用 python 和正则表达式,下面是我的实现,我的 python 代码中有这个函数:

    def cplusComment(self,content):
       for comment in re.findall(r'\/\*((.*?)|(\n))*\/', content, re.S):
           yield comment

上面的函数在这部分代码中被调用:

    def commentdata(self, content):
        for con in content.read():
           for k in self.cplusComment(con):
               print(k, 'what is this k meant for')

我的输出是这种格式的空列表:

    ('', '', '')

我所期待的应该是

    this is a comment in C. This comment syntax is guaranteed to work
    on every compiler
    This is also a comment in C. but it might present portability
    challenges
    This is multi line comment in C++

如果我能指引正确的方向,我将不胜感激

标签: pythonc++regex

解决方案


如果不构建完整的 C 解析器,就无法可靠地解决这个问题,因为存在字符串和嵌套注释,并且/*序列可以很容易地位于字符串内部,例如printf( "/* is this a comment or what?" );等。

此外,/*有时*/用于注释部分代码,有时是相当大的块,而不用注释每一行//,这些代码块是您想要作为程序输出获得的注释吗?可能不是...

这是一个链接,可能会让您朝着正确的方向前进:Complete C99 parser in pure Python


推荐阅读