Python equivalent of Perl's $/
attn.steven.kuo at gmail.com
attn.steven.kuo at gmail.com
Mon Aug 20 18:02:05 EDT 2007
On Aug 20, 1:02 pm, John K Masters <johnmast... at oxtedonline.net>
wrote:
> On 19:19 Mon 20 Aug , attn.steven.... at gmail.com 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
More information about the Python-list
mailing list