GUIツールの機能概要
このツールでは、以下の3つの削除方法をチェックボックスで選択できます。
オプション | 説明 |
---|---|
コメント中の日本語を削除 | # で始まり、日本語を含むコメントを削除 |
行末の日本語コメントを削除 | コード末尾の日本語コメントを削除(コード本体は保持) |
日本語を含む行を全て削除 | # の有無に関係なく、日本語のある行そのものを削除 |
GUIでファイルを選び、実行ボタンを押すだけで別ファイルとして保存されます(例:test.py
→ test_cleaned.py
)。
実際のコード全文(コピペOK)
import tkinter as tk
from tkinter import filedialog, messagebox
import re
import os
def remove_comments(file_path, opt_comment, opt_tail, opt_all):
if not file_path.endswith(".py"):
messagebox.showerror("エラー", "Pythonファイル(.py)を選択してください。")
return
new_file_path = file_path.replace(".py", "_cleaned.py")
try:
with open(file_path, "r", encoding="utf-8") as input_file, \
open(new_file_path, "w", encoding="utf-8") as output_file:
for line in input_file:
# 日本語行の削除
if opt_all and re.search(r'[ぁ-んァ-ン一-龥]', line):
continue
if opt_tail:
line = re.sub(r'#.*[ぁ-んァ-ン一-龥]+.*$', '', line)
if opt_comment:
line = re.sub(r'#.*[ぁ-んァ-ン一-龥]+.*', '', line)
output_file.write(line)
messagebox.showinfo("完了", f"処理が完了しました:\n{new_file_path}")
except Exception as e:
messagebox.showerror("エラー", f"処理中にエラーが発生しました:\n{e}")
def select_file():
file_path = filedialog.askopenfilename(
title="Pythonファイルを選択",
filetypes=[("Python files", "*.py")]
)
if file_path:
entry_path.delete(0, tk.END)
entry_path.insert(0, file_path)
def run_removal():
file_path = entry_path.get()
if not file_path:
messagebox.showwarning("警告", "ファイルを選択してください。")
return
opt_comment = var_comment.get()
opt_tail = var_tail.get()
opt_all = var_all.get()
if not (opt_comment or opt_tail or opt_all):
messagebox.showwarning("警告", "少なくとも1つのオプションを選択してください。")
return
remove_comments(file_path, opt_comment, opt_tail, opt_all)
# GUIセットアップ
root = tk.Tk()
root.title("日本語コメント削除ツール(統合版)")
root.geometry("520x260")
label = tk.Label(root, text="処理するPythonファイルを選択してください:")
label.pack(pady=10)
frame = tk.Frame(root)
frame.pack()
entry_path = tk.Entry(frame, width=50)
entry_path.pack(side=tk.LEFT, padx=5)
btn_browse = tk.Button(frame, text="参照", command=select_file)
btn_browse.pack(side=tk.LEFT)
# チェックボックス
options_frame = tk.LabelFrame(root, text="削除オプション", padx=10, pady=10)
options_frame.pack(pady=15)
var_comment = tk.BooleanVar()
var_tail = tk.BooleanVar()
var_all = tk.BooleanVar()
tk.Checkbutton(options_frame, text="コメント中の日本語を削除", variable=var_comment).pack(anchor="w")
tk.Checkbutton(options_frame, text="行末の日本語コメントを削除", variable=var_tail).pack(anchor="w")
tk.Checkbutton(options_frame, text="日本語を含む行を全て削除", variable=var_all).pack(anchor="w")
btn_run = tk.Button(root, text="実行", command=run_removal, bg="#007ACC", fg="white", height=2, width=25)
btn_run.pack(pady=10)
root.mainloop()
実行イメージ

- ファイル選択 → チェック → 実行 → 新しいファイルに保存
- 元のファイルは変更されないので安心
まとめ
- Pythonファイル中の日本語コメント削除をGUIで手軽に実行
- 正規表現を使った柔軟なフィルタ処理が可能
- スクリプトベースでも、業務効率化にも使える