perl to python, case + regular expression question

Andrew Dalke dalke at acm.org
Tue Jul 25 17:56:12 EDT 2000


Jim McKim wrote in message ...
>I've got a question about what would be a good way in python to
>express an operation that needs to be done fairly often in this
>project.
>
>The operation (parsing log files) in perl would look like:
>
>if ($input_line =~ /^log entry (\d+)/) {
>    my $log_entry_num = $1;
>    ...etc.
>}
>elsif ($input_line =~ /^run number (\d+) timestamp (.*)/) {
>    my $run_number = $1;
>    my $timestamp = $2;
>    ...etc.
>}

in addition to the comments others said about using re, you should
know that a more Pythonic way to do this might be

words = string.split(input_line)
if words.get(0, None) == "log":
  log_entry_num = int(words[2])
elif words.get(0, None) == "run":
  run_number = int(words[2])
  timestamp = string.join(words[4:])

This is *not* the same as the perl code, since it doesn't check for
"log rolling 5" and assumes any whitespace in the timestamp is a single
space used for a separator (which is probably true).  However, if the
vocabulary of the input file is restricted, which is linkely is, then
you'll find that the above approach is probably faster than using re.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list