我有一个由一家建筑公司创建并使用的数据库。所有测量数据都以这样的格式存储:15-3/4"和12‘6-3/4"。
有没有办法将这些类型的度量转换为Python中的浮点?还是有一个库提供了这个功能?
同样,如何将浮点转换为上述格式?
发布于 2011-12-30 06:33:01
根据模式的规则性,您可以使用http://docs.python.org/library/stdtypes.html#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
发布于 2011-12-30 05:56:44
考虑下面的自注释代码。我试着保持简单
>>> 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
从浮点转换到体系结构将很容易,因为您不需要承受解析的痛苦
>>> 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)
发布于 2011-12-30 03:24:46
从建筑到浮点:
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"
才能被正确地解析。
https://stackoverflow.com/questions/8675714
复制相似问题