[Tutor] Re: display filter slow [pyperl and Text::Autoformat]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 18 Dec 2001 14:48:34 -0800 (PST)


[Warning: this post mentions the use of the pyperl module; those with weak
constitution to Perl should skip this message.]






Perl actually has a very nice module called Text::Autoformat that does a
very good job at justifying messages, especially email messages.

http://search.cpan.org/doc/DCONWAY/Text-Autoformat-1.04/lib/Text/Autoformat.pm

It is one of the nicest test formatters I've ever seen.  One of its
"downsides", though, is that it's in Perl.


This shouldn't stop us from considering it, though.  It's quite possible
to use Perl modules in Python, through the really cool 'pyperl' module:

    http://downloads.activestate.com/Zope-Perl/pyperl-1.0.1.tar.gz

pyperl makes using Perl modules almost transparent from Python.  I've
written a small wrapper below to simplify the use of Text::Autoformat in
Python.


###
"""autoformat.py: A small Python wrapper class for Perl's Text::Autoformat
module. This uses pyperl.

Example use:

    import autoformat
    rawtext = '''Hello world, this is a test of the emergency broadcast
    system.  This is only a test.  muahahahahaha
    this is quite neat.'''
    ## A simple call using all defaults.
    formatted = autoformat(rawtext)
    ## Calls that override the defaults with some options.
    formatted = autoformat(rawtext, left=8, right=70)
    formatted = autoformat(rawtext, justify='right')
"""

import perl
perl.eval("use Text::Autoformat;")

def autoformat(mystring, **kwargs):
    kwarg_ref = perl.get_ref('%')
    kwarg_ref.update(kwargs)
    return perl.call("autoformat", mystring, kwarg_ref)
###



Here's a sample session that uses this wrapper:

###
>>> sample_msg = """> On Mon, 17 Dec 2001 Prahlad Vaidyanathan spewed into
the ether:
> [-- snip --]
> > As you can see, the script takes nearly thrice the amount of time as
> > without it. I'm sure there is a more efficient way of filtering my
mail,
> > so any help would be appreciated."""
>>> print autoformat(sample_msg, left=8, right=60, all=1)
       > On Mon, 17 Dec 2001 Prahlad Vaidyanathan spewed
       > into the ether: [-- snip --]
       > > As you can see, the script takes nearly thrice
       > > the amount of time as without it. I'm sure there
       > > is a more efficient way of filtering my mail, so
       > > any help would be appreciated.
###


I thought this was pretty darn neat.  *grin*  Hope this helps!