python - 使用 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++
如果我能指引正确的方向,我将不胜感激
解决方案
如果不构建完整的 C 解析器,就无法可靠地解决这个问题,因为存在字符串和嵌套注释,并且/*
序列可以很容易地位于字符串内部,例如printf( "/* is this a comment or what?" );
等。
此外,/*
有时*/
用于注释部分代码,有时是相当大的块,而不用注释每一行//
,这些代码块是您想要作为程序输出获得的注释吗?可能不是...
这是一个链接,可能会让您朝着正确的方向前进:Complete C99 parser in pure Python
推荐阅读
- java - 有没有办法删除链接列表节点,以使这段代码中的头部成为唯一剩下的东西?
- javascript - 将 jQuery ajax 转换为 fetch
- typescript - 高级 TS 类型:镜像键但成为新值的包装器类型
- flutter - 收听 FutureProvider 的变化
- php - PHP“填充”函数参数
- javascript - 如何在电子中有多个页面?
- android - CameraX ,捕获图像表面视图并发送 firebase
- windows - 在知道父进程句柄的情况下,如何获取子进程句柄?
- c# - 使用 itext7 .NET 为标记 (FreeText) PDF 设置图层
- go - 为什么播种和生成随机数会阻止 bufio 扫描仪在 Go 中读取文件中的行?