需求
在申请软著的时候,需要提交源码。源码中不能包含注释,因此写了一个Python3脚本来删除这些注释
代码
下面展示一些 内联代码片
。
import re
import os
def remove_cs_comments(filename):
# 正则表达式,匹配//及其后面的内容
pattern = re.compile(r'//.*')
with open(filename, 'r', encoding='utf-8') as file:
content = file.read()
# 使用正则表达式替换掉所有匹配的内容为空字符串
new_content = re.sub(pattern, '', content)
# 保存修改后的内容
with open(filename, 'w', encoding='utf-8') as file:
file.write(new_content)
return new_content
# 指定要遍历的文件夹路径
folder_path = r'E:\Develop-Software\PyCharm\Projects'
# 遍历文件夹中的所有.cs文件
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.cs'):
filename = os.path.join(root, file)
remove_cs_comments(filename)
print("remove done!")