读入一个Python程序,将其单行的注释(即 每一行“#”后面的内容)删除后程序中的注释后显示
时间: 2023-12-03 15:42:18 浏览: 37
很好的问题,以下是解决方案:
```python
with open("program.py", "r") as f:
for line in f:
line = line.split("#")[0].strip()
if line:
print(line)
```
这个程序会打开名为 "program.py" 的文件,逐行读取并删除单行注释,然后打印出没有注释的代码行。
相关问题
读入一个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!')
```