Advertisement
Guest User

Untitled

a guest
Oct 2nd, 2014
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import fileinput
  2.  
  3.  
  4. def find_comments(text):
  5.     """Returns an iterable of comments in python source"""
  6.     quote = ''  # ' or " if inside string literal
  7.     escape = False  # true, if current symbol is escaped
  8.  
  9.     for line in text:
  10.         # remove trailing carriage return
  11.         line = line.rstrip('\n')
  12.  
  13.         if not escape:
  14.             quote = ''
  15.  
  16.         for i in range(len(line)):
  17.             # if current symbol is '#', and it is not quoted
  18.             if line[i] == '#' and not quote:
  19.                 yield line[i:]  # return the rest of string
  20.                 break
  21.  
  22.             # update the state of quote flag
  23.             if line[i] == quote and not escape:
  24.                 quote = ''
  25.             elif line[i] in '\'"' and not quote:
  26.                 quote = line[i]
  27.  
  28.             # update the state of escape flag
  29.             escape = (line[i] == '\\') and not escape
  30.  
  31.  
  32. for comment in find_comments(fileinput.input()):
  33.     print(comment)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement