如何将以建筑格式显示的测量值转换为浮点?

2024-04-26 00:43:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据库,是由一家建筑公司创建和使用的。所有测量值都以如下格式存储:15-3/4“12'6-3/4”。在

有没有一种方法可以在Python中将这些类型的度量转换成浮点?或者有一个库提供这个功能吗?在

同样,如何将浮点转换为上述格式?在


Tags: 方法功能数据库类型度量格式公司中将
3条回答

根据模式的规则性,您可以使用str.partition来进行解析:

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

体系结构到浮点:

import re

regex = re.compile('(\d+\' )*(\d+)-(\d+)\/(\d+)"')
regex.sub(lambda m: str((int((m.group(1) or '0').split("'")[0]) * 12)
  + int(m.group(2)))
  + ('%.2f' % (int(m.group(3)) / float(m.group(4))))[1:], measurement)

这真的很糟糕,但我已经有一段时间没有使用Python了;我不怀疑有一种更干净的方法来实现这一点,但它确实很好地处理了缺少脚的问题。但是,它总是期望英寸,所以像12'这样的测量必须是12' 0"才能正确解析。在

考虑下面的自注释代码。我尽量保持简单

>>> from fractions import Fraction
>>> def Arch2Float(num):
    #First Partition from Right so that the Feet and Unit always
    #Remains aligned even if one of them is absent
    ft,x,inch=num.rpartition("\'")
    #Convert the inch to a real and frac part after stripping the
    #inch (") identifier. Note it is assumed that the real and frac
    #parts are delimited by '-'
    real,x,frac=inch.strip("\"").rpartition("-")
    #Now Convert every thing in terms of feet which can then be converted
    #to float. Note to trap Error's like missing or invalid items, its better
    #to convert each items seperately
    result=0
    try:
        result = int(ft.strip("\'"))
    except ValueError:
        None
    #Convert the real inch part as a fraction of feet
    try:
        result +=  Fraction(int(real),12)
    except ValueError:
        None
    #Now finally convert the Fractional part using the fractions module and convert to feet
    try:
        result+=Fraction(frac)/12
    except ValueError:
        None
    return float(result)    

酸性试验

^{pr2}$

从Float到Architecture的转换将很容易,因为您不必忍受解析的痛苦

>>> def Float2Arch(num):
    num=Fraction(num)
    ft,inch=Fraction(num.numerator/num.denominator),Fraction(num.numerator%num.denominator)/num.denominator*12
    real,frac=inch.numerator/inch.denominator,Fraction(inch.numerator%inch.denominator,inch.denominator)
    return '{0}\' {1}-{2}"'.format(ft,real,frac)

酸性试验

>>> print Float2Arch(Arch2Float('12\' 6-3/4"'))
12' 6-3/4"
>>> print Float2Arch(Arch2Float('15-3/4"'))
1' 3-3/4"
>>> print Float2Arch(Arch2Float('12\'6-3/4"'))
12' 6-3/4"
>>> print Float2Arch(Arch2Float('3/4"'))
0' 0-3/4"
>>> print Float2Arch(Arch2Float('15\''))
15' 0-0"
>>> print Float2Arch(Arch2Float('15'))
1' 3-0"
>>> 

注***保持最小分母(英寸)或最高分母(英尺)的浮点数表示非常重要。我选择了最高的脚。如果你不想把它降低,你可以把它乘以12。在


更新以满足取整要求 (不确定这是否优雅,但能起作用)

def Float2Arch(num):
    num=Fraction(num)
    ft,inch=Fraction(num.numerator/num.denominator),Fraction(num.numerator%num.denominator)/num.denominator*12
    real,frac=inch.numerator/inch.denominator,Fraction(inch.numerator%inch.denominator,inch.denominator)
    for i in xrange(1,17):
        if Fraction(frac) < Fraction(1.0/16*i): break
    frac=Fraction(1.0/16*i)
    if frac>= 1:
        real+=1
        frac=0
    return '{0}\' {1}-{2}"'.format(ft,real,frac)

相关问题 更多 >