代碼
"""
利用正則表達式去除文件中的單行注釋,支持多行稍加更改即可
"""
import os
import re
pattern_c = {re.compile(r'//.*'), re.compile(r'/\*.*?\*/'), }
# /* ... /* ... */ 應該是首尾的進行匹配而不是第二個和末尾匹配
# 去c/c++單行注釋(可改成多行),匹配 // /**/ 兩種注釋
pattern_cpp = pattern_c
pattern_py = {re.compile(r'#.*'), re.compile(r'(""".*?""")*|(\'\'\'.*?\'\'\')*'), }
pattern_js = pattern_c
pattern_html = {re.compile(r'<!--.*?-->'), }
pattern_less = pattern_c
pattern_wxml = pattern_html
pattern_vue = {*pattern_html, *pattern_js, *pattern_less, }
pattern_map = {
'c': pattern_c,
'cpp': pattern_c,
'py': pattern_py,
'js': pattern_js,
'html': pattern_html,
'less': pattern_less,
'wxml': pattern_wxml,
'vue': pattern_vue,
}
def parse(string, ext='py'):
"""
去某一字符串包含的注釋,默認處理python文件
"""
if ext not in pattern_map:
return string
result = string
for p in pattern_map[ext]:
result = re.sub(p, "", result)
return result
def parse_file(file_path, output='string'):
"""
去除某一源碼文件的注釋,並將修改后的字符串寫入新文件
由於是一行行處理,無法去除多行注釋,先讀出整個content再處理即可支持多行(也要pattern支持)
"""
name, ext = os.path.splitext(file_path)
content = ""
with open(file_path, "r", encoding='utf-8') as f:
for line in f:
# res_f.writeline(parse(line))
content += parse(line, ext[1:])
# 不要后綴前面的dot
new_file_path = f"{name}_noC{ext}"
if output == 'string':
return content
elif output == 'file':
with open(new_file_path, "w", encoding='utf-8') as f:
f.write(content)
return new_file_path
if __name__ == "__main__":
try:
parse_file(file_path=r'H:\folder\test.py', output='file')
except Exception as e:
print(e)
input("處理完成")
使用
- 修改入口parse_file的參數,output='file'會生成去除了注釋后的文件
- 本意是與代碼統計腳本搭配