?? Automate Comment Removal or Replacement in Code (Java) Files with Python ??

?? Automate Comment Removal or Replacement in Code (Java) Files with Python ??

Hey everyone! ??

I recently developed a Python script that can help automate the process of managing comments in Java files. Whether you need to find, remove, or replace specific comments, this script can do it all! ??

?? Features:

  • Find specific comments (e.g., //ok, // ok with some text, etc.)
  • Remove lines containing comments that match a specific pattern (e.g., //ok with or without spaces)
  • Replace any specific comment or pattern with new content
  • Flexible to choose file types (e.g., .java, .py, etc.)
  • Allow users to specify which directory to search in
  • Safe file modifications (it only writes back if changes are made)

?? How It Works:

  1. Choose the directory where you want to search for files.
  2. Select the operation (find, remove, or replace comments).
  3. Specify the file type (e.g., .java, .txt).
  4. The script processes files and makes changes safely.


import os
import re

def find_comments(directory, pattern, file_type=".java"):
    # Regular expression to match the pattern
    comment_pattern = re.compile(pattern)
    files_with_comments = []

    # Walk through all files in the given directory
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(file_type):  # Process only specified file type
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.readlines()  # Read file line by line

                    # Check each line for the pattern
                    for line_num, line in enumerate(content, 1):
                        if comment_pattern.match(line):
                            files_with_comments.append((file_path, line_num, line.strip()))

                except Exception as e:
                    print(f"Error reading file {file_path}: {e}")

    return files_with_comments


def remove_comments(directory, pattern, file_type=".java"):
    # Regular expression to match the pattern
    comment_pattern = re.compile(pattern)
    modified_files = []

    # Walk through all files in the given directory
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(file_type):  # Process only specified file type
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.readlines()  # Read file line by line

                    # Remove lines that match the pattern
                    new_content = [line for line in content if not comment_pattern.match(line)]

                    # If content has changed, write the new content back to the file
                    if len(new_content) != len(content):
                        with open(file_path, 'w', encoding='utf-8') as f:
                            f.writelines(new_content)
                        modified_files.append(file_path)

                except Exception as e:
                    print(f"Error reading/writing file {file_path}: {e}")

    return modified_files


def replace_comments(directory, pattern, replacement, file_type=".java"):
    # Regular expression to match the pattern
    comment_pattern = re.compile(pattern)
    modified_files = []

    # Walk through all files in the given directory
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(file_type):  # Process only specified file type
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.readlines()  # Read file line by line

                    # Replace lines that match the pattern
                    new_content = [comment_pattern.sub(replacement, line) for line in content]

                    # If content has changed, write the new content back to the file
                    if new_content != content:
                        with open(file_path, 'w', encoding='utf-8') as f:
                            f.writelines(new_content)
                        modified_files.append(file_path)

                except Exception as e:
                    print(f"Error reading/writing file {file_path}: {e}")

    return modified_files


# Example Usage:
# 1. Find lines with "https://ok"
# result = find_comments("/path/to/your/directory", r"^\s*//\s*ok\s*$")
# print(result)

# 2. Remove lines with "https://ok"
# result = remove_comments("/path/to/your/directory", r"^\s*//\s*ok\s*$")

# 3. Replace "https://ok" with "https://TODO"
# result = replace_comments("/path/to/your/directory", r"^\s*//\s*ok\s*$", "https://TODO")        

要查看或添加评论,请登录

ROKI ROY的更多文章

社区洞察

其他会员也浏览了