Wednesday 16 February 2011

Creating Bike routes: Now with added python

# Help yourself to this. If you find a bug or improve on it, please let me have a copy back!
# (c) Gareth Evans Feb 2011

# Format of data is
#<coordinates>x,y</coordinates>
#or
#<coordinates>
#x,y
#</coordinates>
#or
#<coordinates>x,y
#x,y</coordinates>
#etc


#Output format is
#From:<longitude>,<latitude><n*<space>to:<longitude>,<latitude>>
#Keep first and last lines, delete 1 in n lines, so total number of lines is 25

import sys, optparse

def write (where, what):
    #print what
    where.write (what)

def printStack (output, stack):
    count = 0
    modulus = 1 + len(stack) / 22
    print  "Stack size %d mod %d "%(len (stack), modulus)
    while len (stack):
        myline = stack.pop(0)
        if count == 0:
            myline = "from:" + myline + " "
            write (output, myline)
        else:
            if not (count % modulus):  
                myline = "to:" + myline + " "
                write (output, myline)
        count += 1

    myline = "to:" + myline + " "
    write (output, myline)



def main (options, args):
    image = open(options.image, "r").readlines()
    print "len %d name %s" % (len(image), options.image)
    namebody = options.image.split('.')
    name = "output_" + namebody[0] + ".txt"
    print name
    output = open (name, "w")

    coordinate = 0
    stack = []
    print "len image %d" % len(image)

   
    while len(image):
        myline = image.pop (0)
        pos = myline.find("<coordinates>")
        #print "coords %d pos %d len image %d data %s" % (coordinate, pos, len(image), myline)

        if coordinate == 0:
            if pos >= 0:
                coordinate = 1

        if coordinate == 1:
            if pos >= 0:
                data = myline[(pos + len("<coordinates>")):].split(',')
            else:
                data = myline.split(',')
            if (len(data) > 1):
                stack.append ("%s,%s" % (data[1], data[0]))
            if myline.find("</coordinates>") >= 0:
                coordinate = 0
       
    printStack (output, stack)

if __name__ == '__main__':
    option_parser = optparse.OptionParser()
    option_parser.add_option('-i', '--image', dest='image', help=' image', default='./file.txt')
    options, args = option_parser.parse_args(sys.argv[1:])

    main (options, args)

No comments:

Post a Comment