BUG:
- 目前输出的文件中可能会出现缩进错误,待修改。
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:
# Before removing the comment, save the indentation of the parent node
parent_indentation = comment.parent.absolute_bounding_box.top_left.column
comment.parent.remove(comment)
# After removing the comment, check if the next sibling is not indented
next_sibling = comment.next
if next_sibling and next_sibling.absolute_bounding_box.top_left.column < parent_indentation:
# Indent the next_sibling to match the parent's indentation
next_sibling.indent(parent_indentation // 4) # Assuming 4 spaces per indentation level
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? (y/n): ").lower() == 'y'
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()
标签:comment,文件,删除,parent,py,next,file,endl
From: https://www.cnblogs.com/yhm138/p/17916146.html