萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 移除 .py 檔案註解工具:ConfigParser 設定 + 正則過濾 + 批量處理

功能需求

  • 讀取 INI 設定檔指定來源/目標資料夾。
  • 遞迴掃描 .py 檔案。
  • 移除 # 開頭的整行註解、行尾內聯註解。
  • 保留 """docstring"""、'''docstring'''、字串字面值中的 #。
  • 輸出處理後檔案至目標資料夾,產生變更日誌。

核心邏輯:智慧型註解判斷

import re

# 忽略行正則:字串字面值中的 # 不視為註解
IGNORE_PATTERNS = [
    r'""".*#.*"""', r"'''.*#.*'''",   # 多行字串內的 #
    r'".*#.*"', r"'.*#.*'",           # 單行字串內的 #
]

def is_ignorable_line(line):
    for pat in IGNORE_PATTERNS:
        if re.search(pat, line):
            return True
    return False

def strip_comments(source_path, dest_path):
    with open(source_path, "r", encoding="utf-8") as f:
        lines = f.readlines()

    new_lines = []
    log_entries = []
    for lineno, line in enumerate(lines, 1):
        stripped = line.rstrip("\n")
        if not stripped.strip() or lineno <= 3 or is_ignorable_line(stripped):
            # 空行、前 3 行(通常為 shebang/encoding/模組文件字串)、字串內 # 保留原樣
            if stripped.strip():
                new_lines.append(line)
            continue

        idx = stripped.find("#")
        if idx == -1:
            new_lines.append(line)
        elif idx == 0:
            # 整行註解:略過,記錄日誌
            log_entries.append(f"Line {lineno}: {stripped}")
        else:
            # 行尾註解:切除
            new_lines.append(stripped[:idx].rstrip() + "\n")
            log_entries.append(f"Line {lineno}: {stripped[idx:]}")

    with open(dest_path, "w", encoding="utf-8") as f:
        f.writelines(new_lines)
    return log_entries

主程式流程

import os, configparser

def main():
    cfg = configparser.ConfigParser()
    cfg.read("CleanNote.ini")
    src = cfg.get("CleanNote", "SrcPath")
    dst = cfg.get("CleanNote", "DescPath")

    os.makedirs(dst, exist_ok=True)

    all_logs = []
    for root, _, files in os.walk(src):
        for fname in files:
            if fname.endswith(".py"):
                src_file = os.path.join(root, fname)
                rel = os.path.relpath(src_file, src)
                dst_file = os.path.join(dst, rel)
                os.makedirs(os.path.dirname(dst_file), exist_ok=True)
                logs = strip_comments(src_file, dst_file)
                if logs:
                    all_logs.append(f"\n=== {rel} ===\n" + "\n".join(logs))

    with open(os.path.join(dst, "CleanNoteLog.txt"), "w", encoding="utf-8") as f:
        f.write("\n".join(all_logs))
    print("完成,日誌見 CleanNoteLog.txt")

if __name__ == "__main__":
    main()

CleanNote.ini 範例

[CleanNote]
SrcPath = E:/project/src
DescPath = E:/project/src_nocomments

限制與改良

  • 正則法無法完美處理巢狀三引號、原始字串 r"#"、f-string 內 # 等邊界情況。
  • 生產級方案:使用 tokenize 模組(標準庫)按 Token 精確識別註解 tokenize.COMMENT,100% 準確。
  • 支援 # type: ignore 等特殊註解保留選項。

tokenize 版核心片段

import tokenize, io

def strip_comments_tokenize(source_path, dest_path):
    with open(source_path, "rb") as f:
        tokens = tokenize.tokenize(f.readline)
    out = []
    last_line = 1
    for tok in tokens:
        if tok.type == tokenize.COMMENT:
            continue
        if tok.type == tokenize.NL or tok.type == tokenize.NEWLINE:
            out.append("\n")
        elif tok.type != tokenize.ENCODING and tok.type != tokenize.ENDMARKER:
            # 補齊行間空白
            if tok.start[0] > last_line:
                out.append("\n" * (tok.start[0] - last_line))
            out.append(" " * (tok.start[1] - len("".join(out).split("\n")[-1])))
            out.append(tok.string)
            last_line = tok.end[0]
    with open(dest_path, "w", encoding="utf-8") as f:
        f.write("".join(out))
copyright © 萬盛學電腦網 all rights reserved