Created
March 20, 2014 20:25
-
-
Save shashi/9673056 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def remove_comments(line, pref="", ctx=None, escape=False): | |
if line == "": return pref | |
if ctx == "#" and line[0] != '\n': | |
return remove_comments(line[1:], pref, ctx) | |
if not ctx: | |
if line[0] == "#": return remove_comments(line[1:], pref, '#') | |
for c in ['"""', '"', "'"]: | |
if line.startswith(c): | |
# open context | |
return remove_comments(line[len(c):], pref + c, c) | |
if ctx and line.startswith(ctx): | |
# close context | |
if not escape: | |
return remove_comments(line[len(ctx):], pref + ctx, None) | |
# carry over context | |
if ctx != '"""' and line[0] == '\n': | |
ctx = None | |
return remove_comments(line[1:], pref + line[0], ctx, | |
not escape and line[0] == '\\') | |
tests = ['', '1; #a', '1; 1', '"" #"', '"a; #b"', '"a; #b" #c', '"a; # d \n b # c"', '"""a #c \n b #d""" #e', '"\\"" # test', '""#a\n""#b'] | |
for t in tests: | |
print t, '->', remove_comments(t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment