去除包含中文字符的代码行

查看 54|回复 3
作者:Mis16800   
去除包含中文字符的代码行

import os
import re
def remove_chinese_code_and_comments_in_folder(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file_name in files:
            if file_name.endswith((".java", ".js", ".py")):
                file_path = os.path.join(root, file_name)
                with open(file_path, "r", encoding="utf-8") as file:
                    code = file.read()
                cleaned_code = remove_chinese_code_and_comments(code)
                with open(file_path, "w", encoding="utf-8") as file:
                    file.write(cleaned_code)
def remove_chinese_code_and_comments(code):
    lines = code.split('\n')
    result = []
    in_comment_block = False
    for line in lines:
        # 去除包含中文字符的注释行
        if "//" in line or "#" in line or "/*" in line:
            if "//" in line:
                line_parts = line.split('//', 1)
            elif "#" in line:
                line_parts = line.split('#', 1)
            else:
                line_parts = re.split('/\*', line, 1)
            comment = line_parts[-1].strip()
            if re.search('[\u4e00-\u9fff]', comment):
                line = line_parts[0]
        # 去除包含中文字符的代码行
        if re.search('[\u4e00-\u9fff]', line):
            line = ""
        if '"""' in line or "'''" in line or "*/" in line:
            in_comment_block = not in_comment_block
        result.append(line)
    return '\n'.join(result)
# 指定要处理的文件夹路径
folder_path = "文件夹路径文件夹路径"
remove_chinese_code_and_comments_in_folder(folder_path)

中文, 字符

gzsklsskszngc   

感谢分享!
cenoser795   

感谢,有用!
Mis16800
OP
  

如果是上传代码到git就可以用来删除中文再上传
您需要登录后才可以回帖 登录 | 立即注册

返回顶部