Junior — Middle
What methods can be used to automatically detect and remove commented sections of code?
sobes.tech AI
Answer from AI
To automatically detect and remove commented sections of code in Python, you can use a static code analyzer or write a script that parses files and removes comments. For example, the ast module can analyze the code structure, but it does not store comments. Therefore, it is easier to use regular expressions or specialized tools.
Here's a simple script example for removing single-line comments:
import re
def remove_comments(code):
# Remove lines starting with # (single-line comments)
return re.sub(r'^\s*#.*$', '', code, flags=re.MULTILINE)
with open('script.py', 'r', encoding='utf-8') as f:
code = f.read()
clean_code = remove_comments(code)
with open('script_clean.py', 'w', encoding='utf-8') as f:
f.write(clean_code)
For more complex cases (multi-line comments, docstrings), you can use parsers or tools like autopep8 or flake8 with appropriate plugins.