Newbie Questions: Swithing from Perl to Python

Roy Smith roy at panix.com
Sun Oct 26 08:11:50 EST 2003


In article <%5Gmb.37416$RP2.4260 at twister.tampabay.rr.com>,
 "Luther Barnum" <SpamSucks at rr.com> wrote:

> I see your from the Tampa area also, cool. That part seems pretty easy but
> what I'm looking for is incrementing a counter. I use this all the time for
> summarizing log files. I would probably prefer to keep using Perl but I work
> in a place where Python is used much more than Perl so I want to learn it
> the Python way.
> 
> Here is  another example:
> 
> ex:
> 
> While(<FILE>) {
>     chomp;
>     if(/(\w+    # Date
>     \s+          # Space
>     \d+         # Day
>     \s+          # Space
>     (\w+)         # Server
>     \s+          # Space
>     (\w+)/x) {  # Error
> 
>         $server = $1;
>         $error = $2;
> 
>         $server_totals{$server}++;
>         $error_totals{$error}++;
>     }
> }

Basicly, I'll repeat my advice from yesterday -- check out the re module 
in the on-line library reference.  It implements full Perl-style regular 
expressions, including the ability to grab the value of sub-expressions 
(the $1, $2 stuff).  The Python code will be a little less compact (but, 
IMHO, easier to read) than the Perl code, but every bit of Perl 
functionality above translates directly on a 1-to-1 basis into Python 
using the re module.

Your xxx_totals hashes just become dictionaires in Python.




More information about the Python-list mailing list