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.         for i in range(len(line)):
  14.             # if current symbol is '#', and it is not quoted
  15.             if line[i] == '#' and not quote:
  16.                 yield line[i:]  # return the rest of string
  17.                 break
  18.  
  19.             # update the state of quote flag
  20.             if line[i] == quote and not escape:
  21.                 quote = ''
  22.             elif line[i] in '\'"' and not quote:
  23.                 quote = line[i]
  24.  
  25.             # update the state of escape flag
  26.             escape = (line[i] == '\\') and not escape
  27.  
  28.  
  29. for comment in find_comments(fileinput.input()):
  30.     print(comment)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement