[Tutor] Regex's and "best practice"

Gerrit Holl gerrit at nl.linux.org
Sat Nov 22 17:31:16 EST 2003

Carl D Cravens wrote:
> Subject: [Tutor] Regex's and "best practice"

> I've recently started learning Python... I'm just about finished with the
> Tutorial, and I've been converting a 90-line Perl script I'd written a few
> years ago to see how Python handles it.
> Now, this script doesn't show off Python's strengths...  all it does is
> read through a standard Unix mailbox and print out From: and Subject: in a
> compact format.  (Actually, basically the same index format as Pine.)  So
> it's doing a lot of string manipulation and pattern matching.

You may want to use an entirely different approach to the problem.
You don't need regular expressions at all. A number of high-level
libraries are available for this problem: the mailbox module,
the email module, e.g. The following code won't work because it's
fake, but the solution may look similar to this:

import email, mailbox
for mail in mailbox.UnixMailbox(email.message_from_file):
    print email.Utils.parse_addr(mail["From"])[1], mail["Subject"]

I haven't tested this and it probably won't work, but you can
find the documentation to the email and mailbox modules in the
library documentation. They are very useful modules. You don't
need any regular expression. I myself tend to avoid them as much
of possible, but Perl has a different philosophy ;). What you are
doing, is translating Perl to Python. But it doesn't become
Python then, it becomes translated Perl. Note that I don't know
anything about tranlasting programs since a prerequisite of
porting is knowing at least 2 languages (I don't), but I read
that this mistake is made my PT2-people (Python as a Second Language ;)
so I just note it here.


There are 10^11 stars in the galaxy. That used to be a huge number. But
it's only a hundred billion. It's less than the national deficit! We used
to call them astronomical numbers. Now we should call them economical
-- Ricard Feynmann, Physics Today, February 1989
Asperger Syndroom - een persoonlijke benadering:
Kom in verzet tegen dit kabinet:

More information about the Tutor mailing list