def string_to_weight(weight):
"""Parse the passed string as a weight. Valid formats are 'X kg', 'X kilos', 'X kilograms' etc."""
m = re.search("^\s*(\d+\.?\d*)\s*(kgs?|kilos?|kilograms?)\s*$", weight, re.IGNORECASE)
if m:
return float(m.groups()[0])
else:
raise TypeError("Cannot extract a valid weight from '%s'" % weight)
string_to_weight("23.5 kilos"), string_to_weight("5kg"), string_to_weight("10 kilogram")
(23.5, 5.0, 10.0)
def get_number_and_unit(s):
"""Interpret the passed string 's' as "X units", where "X" is a number and
"unit" is the unit. Returns the number and (lowercased) unit
"""
m = re.search("^\s*(\d+\.?\d*)\s*(\w+)\s*$", s, re.IGNORECASE)
if m:
number = float(m.groups()[0])
unit = m.groups()[1].lower()
return (number, unit)
else:
raise TypeError("Cannot extract a valid 'number unit' from '%s'" % s)
def string_to_height(height):
"""Parse the passed string as a height. Valid formats are 'X m', 'X centimeters' etc."""
(number, unit) = get_number_and_unit(height)
if re.search("cm|centimeters?", unit):
return number / 100.0
elif re.search("m|meters?", unit):
return number
else:
raise TypeError("Cannot convert a number with units '%s' to a valid height" % unit)
def string_to_weight(weight):
"""Parse the passed string as a weight. Valid formats are 'X kg', 'X grams' etc."""
(number, unit) = get_number_and_unit(weight)
if re.search("kgs?|kilos?|kilograms?", unit):
return number
elif re.search("g|grams?", unit):
return number / 1000.0
else:
raise TypeError("Cannot convert a number with units '%s' to a valid weight" % unit)
string_to_height("55 cm"), string_to_height("2m"), string_to_height("15meters")
(0.55, 2.0, 15.0)
string_to_weight("15g"), string_to_weight("5 kilograms"), string_to_weight("5gram")
(0.015, 5.0, 0.005)