Python: Monty Python's Flying Circus

[top]

  1. Object oriented script language.
  2. Simple control structure; "Block by indent".
  3. Example: Cross referencer

    #!/usr/bin/env python
    # tiny cross referencer written in Python
    #
    import math, fileinput, re, string, sys
    name = r"[A-Za-z_][A-Za-z_0-9]*"
    
    # pass 1
    xref = {}
    m = re.compile(name)
    for line in fileinput.input():
        for w in m.findall(line):
            try:
                if not fileinput.lineno() in xref[w]:
                    xref[w].append(fileinput.lineno())
            except KeyError:
                xref[w] = [ fileinput.lineno() ]
    
    # obtain prameter for output
    keys = xref.keys()
    namefmt = "%" + `max(map(len, keys))` + "s"
    lnofmt = "%" + `math.ceil(math.log10(fileinput.lineno()))` + "d"
    
    # pass 2
    keys.sort(lambda a, b: cmp(string.lower(a), string.lower(b)))
    for w in keys:
        print namefmt % w + ":",
        for lno in xref[w]:
            print lnofmt % lno,
        print
    

[top]