使用redbaron删除删除一个.py文件的所有注释,输出到一个新.py文件,文件名加上_nocmts后缀,用户可以自己决定是否保留空行

发布时间 2023-12-20 11:30:43作者: yhm138
from redbaron import RedBaron

def remove_comments_with_redbaron(source_py_file, keep_blank_lines):
    with open(source_py_file, 'r', encoding='utf-8') as file:
        red = RedBaron(file.read())

    # 移除所有注释
    comments = red.find_all('comment')
    for comment in comments:
        comment.parent.remove(comment)

    # 如果不保留空行,则移除所有独立的换行符节点
    if not keep_blank_lines:
        while True:
            endl_nodes = red.find_all('endl')
            if not endl_nodes:
                break
            for endl in endl_nodes:
                if not endl.next_renderable:
                    endl.parent.remove(endl)
    return red.dumps()


def main():
    source_py_file = input("Enter the path to the .py file to clean up: ")
    keep_blank_lines = input("Do you want to keep blank lines? (yes/no): ").lower() == 'yes'
    new_content = remove_comments_with_redbaron(source_py_file, keep_blank_lines)
    new_file_name = source_py_file.replace('.py', '_nocmts.py')
    with open(new_file_name, 'w', encoding='utf-8') as new_file:
        new_file.write(new_content)
    print(f"Cleaned file has been saved as: {new_file_name}")


if __name__ == '__main__':
    main()