欢迎光临散文网 会员登陆 & 注册

自动删除注释python代码

2023-07-17 17:41 作者:盼归云  | 我要投稿

代码分享:

def remove_comments(code):

# 将代码按行分割

lines = code.split('\n')


# 初始化结果列表

result = 【】


# 遍历每一行代码

for line in lines:

# 查找注释符号 '#' 的位置

index = line.find('#')

# 如果找到了注释符号

if index != -1:

# 从该行中删除注释部分

line = line【:index】

# 将处理后的行添加到结果列表中

result.append(line)


# 将结果列表拼接成字符串并返回

return '\n'.join(result)


#打开wen.txt文本进行调用函数

with open('wen.txt',encoding='utf-8',mode='r') as a:

#读

b=a.read()

#调用

c=remove_comments(b)

#打印

print(c)

自动删除注释python代码的评论 (共 条)

分享到微博请遵守国家法律