requestion regarding regular expression
Scott David Daniels
scott.daniels at acm.org
Fri Apr 14 16:57:09 EDT 2006
BartlebyScrivener wrote:
> That's it. Thank you! Very instructive.
>
> Final:
>
> path = "d:/emacs files/emacsinit.txt"
> lines = open(path).readlines()
> # next two lines all on one
> starts = [i for i, line in enumerate(lines) if
> line.startswith('(defun')]
> for i, start in enumerate(starts):
> while start > 0 and lines[start-1].startswith(';'):
> starts[i] = start = start-1
> print starts
>
If you don't want to hold the whole file in memory, this gets the
starts a result at a time:
def starts(source):
prelude = None
for number, line in enumerate(source): # read and number a line
if line[0] == ';':
if prelude is None:
prelude = number # Start of commented region
# else: this line just extends previous prelude
else:
if line.startswith('(defun'):
# You could append to a result here, but yield lets
# the first found one get out straightaway.
if prelude is None:
yield number
else:
yield prelude
prelude = None
path = "d:/emacs files/emacsinit.txt"
source = open(path)
try:
for line in starts(source):
print line,
# could just do: print list(starts(source))
finally:
source.close()
print
--
-Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list