利⽤正则表达式,去除python⽂件中所有注释
简介
有时候代码的注释写的太多,反⽽影响对程序的理解
⼿动删除所有注释代码,⼜过于⿇烦
所以基于 ⽂件读写,异常处理,正则字符串 等知识
写了这么个⼩程序
程序特点
在任意位置终端(cmd)中运⾏此程序,将需要删除注释的.py⽂件,拖拽到终端窗⼝中。都可以在源⽂件路径下,⽣成⽆注释版本的⽂件.py 和 注释的备份 .txt⽂件
源代码
import re
def file_analysis(old_file_lines, six_quotes, hashtap):
"""标记需要删除的注释的⾏号,并存⼊列表"""
i = 0
for line in old_file_lines:
# 符号 # 独占⼀⾏
ret_1 = re.match(r"^[^\w]*#+",line)
if ret_1:
hashtap.append(i)
# 符号 """ 独占⼀⾏
ret_2 = re.match(r"[ ]*\"\"\"",line)
if ret_2:
# 如果存在类型,函数说明的 """xxxxx""" 之类的,不予删除
ret_2_1 = re.match(r"[^\"]*\"\"\"[^\"]*\"\"\"",line)
if ret_2_1:
pass
else:
six_quotes.append(i)
i += 1
# 将两个"""⾏号之间所有的⾏添加到 # 号列表中
while six_quotes != []:
# 从列表中移出最后两个元素
a = six_quotes.pop()
b = six_quotes.pop()
temp = b
while temp <= a:
hashtap.append(temp)
temp += 1
# 返回 # 号列表,记返回需要删除的所有注释的⾏号集合
return hashtap
def main():
""" 主函数"""
# 1,获取路径,并读取此⽂件
# 1.1 获取⽂件名及其路径
print("\r\n"*3)
file_name = input("请输⼊需要删除注释的⽬标⽂件(形如:file.py):")
# 1.2 读取⽂件
try:
f = open(file_name, "rb")
old_file = f.read()
f.close()
f.close()
except:
print("⽆法打开⽂件:" + file_name)
else:
# 2,处理⽂件
# 2.1 读取⽂件成功,⽂件解码并按⾏切割成列表
old_file = old_file.decode("utf-8")
old_file_lines = old_file.splitlines()
# 2.2 处理⽂件并得到需要删除的注释的⾏号集合
six_quotes, hashtap = list(), list()
hashtap = file_analysis(old_file_lines, six_quotes, hashtap)  # 此时返回值 hashtap列表中,不仅仅包含#,还有"""的⾏号  try:
# 3,获取注释和⽆注释内容到列表中
# 3.2 去重并排序,得到所有注释⾏号的列表
comment_list = sorted(set(hashtap))
# 3.3 创建存储(备份)注释⽂件内容的列表
comment_file = list()
for i in comment_list:
comment = old_file_lines[i]
comment_file.append(comment)
# 创建与源⽂件总⾏号相同的列表 0,1,
new_file_list = list(i for i in range(len(old_file_lines)))
# 删除注释的⾏号,留下⽆注释的⾏号的列表集合
for i in comment_list:
new_ve(i)
# 3.4 创建存储(⽆注释)新⽂件内容的列表
new_file_lines = list()
for i in new_file_list:
temp = old_file_lines[i]
new_file_lines.append(temp)
except:
print("待处理代码中没有注释")
else:
# 4,在⽂件路径新建两个⽂件,并写⼊数据到⽂件
ret = re.match(r"([^ ]+).py",file_name)
if ret:
file_name_pre = up(1)
# 5,分别新建 “⼲净版”⽂件,和“注释集合”⽂件
with open(file_name_pre + "(⽆注释版).py","wb") as f:
for i in new_file_lines:
f.de("utf-8"))
f.write("\r\n".encode("utf-8"))
with open(file_name_pre + "(注释存档).txt", "wb") as f:
for i in comment_file:
f.de("utf-8"))
f.write("\r\n".encode("utf-8"))
print("\r\n"*3)
print("--------创建成功--------")
print("\r\n"*3)
else:
print("正则字符串,⽆法识别⽂件的路径")
if __name__ == "__main__":
main()
Demo⽰例
print("程序中常见的注释")
注意:此程序将会删除的,会在Demo注释末尾添加 YES,不会删除的 NO # 这是第⼀种注释,'#'放在开头(YES)
ret = analysix(data)  # 这是第⼆种注释,'#'跟在某⼀个语句后⾯(NO)
"""
第三种注释
有时候需要注释掉某⼀整块东西的时候,使⽤这个
(YES)
"""
""" 第四种注释,这是函数或者类的说明(NO)"""
# 这是第四种注释,'#'前⾯加了空格(YES)
运⾏
python正则表达式不包含
⽣成的⽆注释⽂件
print("程序中常见的注释")
注意:此程序将会删除的,会在Demo注释末尾添加 YES,不会删除的 NO ret = analysix(data)  # 这是第⼆种注释,'#'跟在某⼀个语句后⾯(NO)""" 第四种注释,这是函数或者类的说明(NO)"""
⽣成的注释备份⽂件
# 这是第⼀种注释,'#'放在开头(YES)
"""
第三种注释
有时候需要注释掉某⼀整块东西的时候,使⽤这个(YES)
"""
# 这是第四种注释,'#'前⾯加了空格(YES)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。