learning to tolerate python

Python is okay, I guess, but there’s not a hint of music to it. I’m a dyed-in-the-wool Perl programmer since 4.036 days. When I think of how I’ll solve a programming problem, I think in Perl (or, more rarely, in PostScript, but I really have to be pretty off-balance to be thinking in stacks). I’m learning Python because all of the seemingly nifty open source geospatial software uses it, and if I’m to write anything for or about the Raspberry Pi, it seems that Python is the language they officially support on it.

So I’m learning Python by porting some of the simple Perl tools I use around here. It’s painful, not just dealing with the language Fortranesque space-significance, but also physically; I think I put my shoulder out picking up Mark Lutz‘s giant books on Python. The first program I chose to port matches input lines against known words in the system dictionary file. Here’s the Perl version:

#!/usr/bin/perl -w

use strict;
use constant WORDLIST => '/usr/share/dict/words';

my %words;
open(WORDS, WORDLIST);
while () {
    chomp;
    my $word  = lc($_);
    $words{$word}++;
}
close(WORDS);

# now read candidate words from stdin
while (<>) {
  chomp;
  $_=lc($_);
  print $_,"\n" if defined($words{$_});
}

exit;

I most recently used this to look for available call signs that — minus the number — were real words. The input lines from the available call sign list look like this:

VA3PHZ
VA3PIA
VA3PID
VA3PIF
VA3PIH
...

so if I strip out the 3s and run it through the program:

sed 's/3//;' va3_avail.txt | ./callsigncheck.pl

I get one hit: vapid. Which is now my call sign, VA3PID. Moohah.

The Python version is much shorter, and I’m semi-impressed with the nifty little trick in line 5 (aka ‘dictionary comprehension’) which offers some hope for the future of terse, idiomatic code. The fileinput module gives Perlish stdin-or-ARGV[] file input, without which I’m sunk.

#!/usr/bin/python
import fileinput                        # Perl-like file input

# get our wordlist
words={w.lower(): 1 for w in open('/usr/share/dict/words', 'r').read().split()}

# read through input looking for matching words
for l in fileinput.input():
    ll=l.lower().rstrip()
    if words.get(ll, 0):
        print(ll)

(So far, I’ve found the PLEAC – Programming Language Examples Alike Cookbook useful in comparing the languages.)

2 thoughts on “learning to tolerate python”

  1. Actually, I should have used a set comprehension, ‘cos all I really want is membership in a set, not key/value pairs.

Leave a Reply

Your email address will not be published. Required fields are marked *