>>> 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)
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)
根据模式的规则性,您可以使用str.partition来进行解析:
体系结构到浮点:
这真的很糟糕,但我已经有一段时间没有使用Python了;我不怀疑有一种更干净的方法来实现这一点,但它确实很好地处理了缺少脚的问题。但是,它总是期望英寸,所以像
12'
这样的测量必须是12' 0"
才能正确解析。在考虑下面的自注释代码。我尽量保持简单
酸性试验
^{pr2}$从Float到Architecture的转换将很容易,因为您不必忍受解析的痛苦
酸性试验
注***保持最小分母(英寸)或最高分母(英尺)的浮点数表示非常重要。我选择了最高的脚。如果你不想把它降低,你可以把它乘以12。在
更新以满足取整要求 (不确定这是否优雅,但能起作用)
相关问题 更多 >
编程相关推荐