2011-12-30 5 views
8

저는 건축 회사에서 작성하여 사용하는 데이터베이스를 보유하고 있습니다. 모든 측정 값은 15-3/4 "12 '6-3/4"과 같은 형식으로 저장됩니다.아키텍처 형식으로 표시된 측정 값을 부동 소수점으로 변환하는 방법은 무엇입니까?

이러한 유형의 측정 값을 파이썬에서 부동 소수점으로 변환 할 수있는 방법이 있습니까? 아니면이 기능을 제공하는 라이브러리가 있습니까?

마찬가지로 부동 소수점을 위의 형식으로 변환 하시겠습니까? 부동 소수점에 건축

+1

는 방법이있다 : 규칙적인 패턴은 구문 분석을 할 str.partition을 사용할 수 있습니다. 그러나 그것들은 단위가있는 값이므로 직접 부동 소수점으로 변환하는 것은 또한 그것이 될 묵시적 단위를 정의해야 할 것입니다. 당신은 또한 정밀도를 잃을 수 있습니다. – Keith

+1

또한 Django는 웹 프레임 워크 일 뿐이므로 실제로이 작업과 관련이 없습니다. 이제 개체를 만들 수 있습니다. 개체를 만들면 해당 형식이 만들어집니다. 그런 다음 모든 템플릿을 사용할 수 있습니다. – Keith

+0

감사합니다 키스 ... 장고 부분을 제거했습니다. – Clayton

답변

3

을 곱 수 있습니다 물론

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 
+0

숫자가 '3/4'와 같이 분수 인 경우 작동하지 않습니다. 수 있습니다. 당신은 단지 rpartition을 고집하고 싶을뿐입니다 – Abhijit

+0

@Abhijit int/frac 분리를 위해 rpartition을 사용하도록 편집했습니다. 감사합니다. –

+0

이것은 훌륭하게 작동합니다 ... 감사합니다 Raymond! – Clayton

0

:

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) 

정말 끔찍하지만 나는 한 동안 파이썬으로 근무 한 적이없는; 나는 이것을하는 훨씬 더 깨끗한 방법이 있다는 것을 의심하지 않지만, 발의 부족을 잘 처리한다. 따라서 이 항상 인치를 예상하기 때문에 12'과 같은 측정 값은 올바르게 구문 분석되어야 12' 0"이어야합니다.

1

다음과 같은 자체 주석 처리 된 코드를 고려하십시오. 난 당신이

>>> 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) 

산을 구문 분석에 고통을하지 않는 쉬운 것입니다 아키텍처에 플로트에서 변환 간단한

>>> 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)  

산성 시험

>>> print Arch2Float('15-3/4"')  # 15-3/4" (without ft) 
1.3125 
>>> print Arch2Float('12\' 6-3/4"') #12' 6-3/4" 
12.5625 
>>> print Arch2Float('12\'6-3/4"') #12'6-3/4" (without space) 
12.5625 
>>> print Arch2Float('3/4"')  #3/4" (just the inch) 
0.0625 
>>> print Arch2Float('15\'')  #15' (just ft) 
15.0 
>>> print Arch2Float('15')   #15 (without any ascent considered as inch) 
1.25 

을 유지하려고 노력 시험

>>> 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" 
>>> 

참고 *** 플로트 표현을 가장 낮은 분모 (인치) 또는 가장 높은 분모 (피트)로 유지하는 것이 중요합니다. 나는이 경우 가장 높은 것을 선택했다. 당신이 그것을 낮은 wan't 경우 (이 작업 우아하지만 않는 경우 확실하지 않음) 당신은 방법에 따라 반올림 요청 을 수용하기 위해 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) 
+0

@ Keith의 의견에 따르면,이 단위를 추가하고 float 및 단위가있는 구조체 또는 클래스로 부동 소수점을 변환합니다. –

+0

@JesseSmith, 그냥 문자열로 변환하고 단위를 추가해야합니다. @RaymondHettinger를'Float2Arch' 함수와 결합 시켰습니다. 당신은 어떻게해야합니까? (예 : Arch2Float ('12 \ '6-3/4' ')) +'ft'' – Abhijit

+0

@Abhijit. 반환 값을 반올림하여 ** 18.33 **과 같은 입력이 ** 18 '4 "**를 반환하도록 제안 하시겠습니까? – Clayton

관련 문제