On Aug 20, 1:02 pm, John K Masters <[EMAIL PROTECTED]>
wrote:
> On 19:19 Mon 20 Aug     , [EMAIL PROTECTED] wrote:
>
>
>
> > import StringIO
>
> > text = """\
> > To mimic Perl's input record separator in
> > Python, you can use a generator.
> > And a substring test.
> > Perhaps something like the following
> > is what you wanted.
> > """
>
> > mockfile = StringIO.StringIO(text)
>
> > def genrecords(mockfile, sep=".\n"):


(snipped)

>
> Thanks, this also looks like a good way to go but ATM beyond my level of
> Python knowledge. I've not reached the generator chapter yet but I'll
> flag the message and return later.
>
> Regards, John


Some features in Perl can be found in Python, so if you know
the former, then learning the latter ought to go smoothly.  In
any case, here's an updated version of the generator that
avoid repeating an unncessary string search:

def genrecords(mockfile, sep=".\n"):
    """
    """
    buffer = ""
    while True:
        idx = buffer.find(sep) + len(sep)
        while idx >= len(sep):
            yield buffer[:idx]
            buffer = buffer[idx:]
            idx = buffer.find(sep) + len(sep)
        rl = mockfile.readline()
        if rl == "":
            break
        else:
            buffer = '%s%s' % (buffer, rl)
    yield buffer
    raise StopIteration

--
Regards,
Steven






-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to