读入一个Python源程序文件,删除程序中的注释后显示
时间: 2023-12-03 14:42:30 浏览: 88
可以使用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!')
```
阅读全文