python删除C 源程序中的注释信息
时间: 2024-01-10 11:04:15 浏览: 40
要从 C 源程序中删除注释信息,可以使用 Python 中的正则表达式库 re。以下是一个示例代码:
```python
import re
with open('example.c', 'r') as f:
content = f.read()
# 删除单行注释
content = re.sub(r'//.*', '', content)
# 删除多行注释
content = re.sub(r'/\*.*?\*/', '', content, flags=re.S)
with open('example_without_comments.c', 'w') as f:
f.write(content)
```
这段代码首先打开名为 `example.c` 的文件并读取其内容。然后使用正则表达式删除单行注释和多行注释。其中,单行注释的正则表达式为 `//.*`,多行注释的正则表达式为 `/\*.*?\*/`,其中 `.*?` 用于匹配任意字符,但是尽可能少地匹配,以避免匹配到多个多行注释之间的内容。最后,将处理后的内容写入名为 `example_without_comments.c` 的新文件中。
相关问题
读入一个Python源程序,删除程序中的注释后显示
以下是Python代码,注释以 # 开头:
```python
# 这是一个示例程序
print("Hello, World!") # 输出“Hello, World!”
```
删除注释后的代码如下:
```python
print("Hello, World!")
```
读入一个Python源程序文件,删除程序中的注释后显示
可以使用Python自带的ast模块来实现删除Python代码中的注释,下面是一个示例代码:
```python
import ast
def remove_comments(source):
"""
Remove comments from Python source code.
"""
class CommentRemover(ast.NodeTransformer):
def visit(self, node):
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Str):
return None # remove the whole node
return node
parsed = ast.parse(source)
transformer = CommentRemover()
parsed = transformer.visit(parsed)
return ast.unparse(parsed)
# 示例代码
source_code = """
# This is a comment
print("Hello, World!") # This is another comment
"""
print(remove_comments(source_code))
```
输出结果为:
```
print('Hello, World!')
```