8.读入 python 源程序文件practice.py,删除程序中的注释后显示。
时间: 2023-12-03 14:42:13 浏览: 37
可以使用正则表达式来删除 Python 程序中的注释,然后将处理后的程序输出到控制台。
以下是一个示例代码:
```python
import re
with open('practice.py', 'r') as f:
program = f.read()
# 删除单行注释
program = re.sub(r'(^|\s+)#.*', '', program)
# 删除多行注释
program = re.sub(r'(?s)\'.*?\'|\".*?\"|#.*?(\n|\r\n)', '', program)
print(program)
```
这个代码可以同时删除单行注释和多行注释,包括用单引号或双引号括起来的字符串中的 '#' 符号。
相关问题
用python编写读入Python源程序文件practice.py,删除程序中的注释后显示。
可以使用Python自带的ast模块来实现读入Python源程序文件并删除注释的功能。以下是示例代码:
```python
import ast
def remove_comments(node):
"""
删除注释节点
"""
if isinstance(node, ast.AST):
# 删除注释节点
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
if node.value.value.startswith("#"):
return None
# 递归处理子节点
for field, old_value in ast.iter_fields(node):
if isinstance(old_value, list):
new_values = []
for value in old_value:
if isinstance(value, ast.AST):
value = remove_comments(value)
if value is not None:
new_values.append(value)
node.__setattr__(field, new_values)
elif isinstance(old_value, ast.AST):
new_value = remove_comments(old_value)
if new_value is None:
delattr(node, field)
else:
node.__setattr__(field, new_value)
return node
if __name__ == '__main__':
# 读入Python源程序文件
with open("practice.py", "r") as f:
source_code = f.read()
# 解析源程序为AST(抽象语法树)
tree = ast.parse(source_code)
# 删除注释节点
remove_comments(tree)
# 生成新的Python源程序文件
new_source_code = ast.unparse(tree)
# 显示新的Python源程序文件
print(new_source_code)
```
需要注意的是,这段代码只会删除单行注释(以`#`开头的注释),而不会删除多行注释(以`'''`或`"""`包裹的注释)。如果需要删除多行注释,可以在`remove_comments`函数中添加相应的处理逻辑。
读入一个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!')
```