Skip to content

Instantly share code, notes, and snippets.

@carlosplanchon
Last active May 4, 2022 00:34
Show Gist options
  • Save carlosplanchon/a4cc7303132085c00ee669ed4b28154a to your computer and use it in GitHub Desktop.
Save carlosplanchon/a4cc7303132085c00ee669ed4b28154a to your computer and use it in GitHub Desktop.
Code to remove Python Comments.
#!/usr/bin/env python3
"""
Copyright <2022> <Carlos Andrés Planchón Prestes - Carlos Agustín Céspedes Vaucher>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
def get_comments_symbol(text, symbol: str) -> list[str]:
comments = []
i: int = 0
indexes = []
for i in range(len(text)):
if text[i] == symbol:
if len(text) > i + 2:
if text[i] == text[i + 1] == text[i + 2]:
# print("Triple quote.")
if(len(indexes) == 0):
indexes.append(i)
elif len(indexes) == 1:
indexes.append(i + 2)
comments.append(text[indexes[0]: indexes[1] + 1])
indexes = []
return comments
def get_comments_simplequot(text: str) -> list[str]:
return get_comments_symbol(text=text, symbol="'")
def get_comments_doublequot(text: str) -> list[str]:
return get_comments_symbol(text=text, symbol='"')
def remove_comments(source: str) -> str:
comments = get_comments_simplequot(text=source)
for comment in comments:
source = source.replace(comment, "")
comments = get_comments_doublequot(text=source)
for comment in comments:
source = source.replace(comment, "")
lines = source.split("\n")
new_lines = []
for line in lines:
if "#" in line:
line_without_comment = "#".join(line.split("#")[:1]).rstrip(" ")
new_lines.append(line_without_comment)
else:
new_lines.append(line)
source = "\n".join(new_lines)
# print("--- SOURCE ---")
# print(source)
return source
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment