Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a measurement displayed in an architectural format to a floating point?

I have a database that was created and is used by an architecture firm. All measurements are stored in a format like this: 15-3/4" and 12' 6-3/4".

Is there a way to convert these types of measurements into floating point in Python? Or is there a library out there that provides this functionality?

Likewise, how would you convert from a floating point to the above format?

like image 410
Clayton Avatar asked Dec 30 '11 02:12

Clayton


People also ask

How do you convert decimal feet to architectural units?

Setting the Scale factor to 12 in this way will take the distance (which is in Decimal Feet), and multiply it by 12 before displaying it in the desired Unit format, which is now set to Architectural inches. As a result, a dimension for 6.5 feet (in Decimal Feet) will appear in a dimension as 6'-6", and so on.


1 Answers

Depending on how regular the patterns are, you can use str.partition to do the parsing:

def architectural_to_float(text):
    ''' Convert architectural measurements to inches.

        >>> for text in """15-3/4",12' 6-3/4",3/4",3/4',15',15",15.5'""".split(','):
        ...     print text.ljust(10), '-->', architectural_to_float(text)
        ...
        15-3/4"    --> 15.75
        12' 6-3/4" --> 150.75
        3/4"       --> 0.75
        3/4'       --> 9.0
        15'        --> 180.0
        15"        --> 15.0
        15.5'      --> 186.0

    '''
    # See http://stackoverflow.com/questions/8675714
    text = text.replace('"', '').replace(' ', '')
    feet, sep, inches = text.rpartition("'")
    floatfeet, sep, fracfeet = feet.rpartition('-')
    feetnum, sep, feetdenom = fracfeet.partition('/')
    feet = float(floatfeet or 0) + float(feetnum or 0) / float(feetdenom or 1)
    floatinches, sep, fracinches = inches.rpartition('-')
    inchesnum, sep, inchesdenom = fracinches.partition('/')
    inches = float(floatinches or 0) + float(inchesnum or 0) / float(inchesdenom or 1)
    return feet * 12.0 + inches
like image 120
Raymond Hettinger Avatar answered Sep 23 '22 00:09

Raymond Hettinger