Re: Questions from Fraser@europarc.xerox.com

Lou Kates (louk@research.teleride.on.ca)
Mon, 16 Nov 1992 11:06:00 -0500

>
> BTW if people who write useful Python code could mail it to me or at
> least tell me about its existence, I can compile a catalog. If you do
> this within a week or two the catalog can be part of the next release,
> 0.9.8 (I'm going to skip 0.9.7 since a lot has changed since 0.9.7beta).
>

The following is short, uses several python libraries,
illustrates writing a filter and using flags so its good for
learning Python. I think you may have changed the regexp library
since my copy of Python so we might want to change the function
names appropriately.

Lou Kates, louk@research.teleride.on.ca

# swap fields x and y preserving whitespace; skip lines with too few fields
# eg: python swapcols.py -x 2 -y 3 myfile.dat

import getopt, regexp, string, sys

options, files = getopt.getopt(sys.argv[1:], 'x:y:')

x, y = 1, 2
for (flag, value) in options:
if 'x' in flag: x = string.atoi(value)
if 'y' in flag: y = string.atoi(value)
if x > y: x, y = y, x

fp = sys.stdin
if files: fp = open(files[0], 'r')

while 1:
line = fp.readline()
if not line: break
if len(string.split(line)) >= y:
t = (regexp.compile('[ \t]*([^ \t]+)' * y)).exec(line)
(a, b), (c, d) = t[x], t[y]
line = line[:a] + line[c:d] + line[b:c] + line[a:b] + line[d:]
print line[:-1]