Last active
March 8, 2016 22:17
-
-
Save JuanPotato/ac08234354a63cc4495e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python3 | |
import re | |
base = '(\d+\.?\d*)\s*' | |
units = { | |
'kg': { | |
'pattern': ['kg', 'kilogram'], | |
'convert': 2.20462262185, | |
'result': 'lb' | |
}, | |
'g': { | |
'pattern': ['g', 'gram'], | |
'convert': 0.00220462262, | |
'result': 'lb' | |
}, | |
'km': { | |
'pattern': ['km', 'kilometer'], | |
'convert': 0.621371, | |
'result': 'mi' | |
}, | |
'm': { | |
'pattern': ['m(?!i)', 'meter'], | |
'convert': 3.28083989501, | |
'result': 'ft' | |
}, | |
'ft': { | |
'pattern': ['ft', 'feet'], | |
'convert': 0.3048, | |
'result': 'm' | |
}, | |
'yd': { | |
'pattern': ['yd', 'yard'], | |
'convert': 0.9144, | |
'result': 'm' | |
}, | |
'lb': { | |
'pattern': ['lb', 'pound'], | |
'convert': 0.45359237, | |
'result': 'kg' | |
}, | |
'mi': { | |
'pattern': ['mile', 'mi'], | |
'convert': 1.60934449789, | |
'result': 'km' | |
}, | |
'acres': { | |
'pattern': ['acre'], | |
'convert': 4046.8564224, | |
'result': 'km^2' | |
}, | |
'C': { | |
'pattern': ['C', 'Celsius'], | |
'convert': lambda c: 1.8*c+32, | |
'result': '°F' | |
}, | |
'F': { | |
'pattern': ['F(?!t)', 'Fahrenheit'], | |
'convert': lambda f: (f-32)/1.8, | |
'result': '°C' | |
} | |
} | |
def convert(text): | |
messages = [] | |
for name, unit in units.items(): | |
pattern = base + '(%s)s?' % '|'.join(unit['pattern']) | |
for match in re.finditer(pattern, text, re.I): | |
start = match.start() | |
value = float(match.groups()[0]) | |
if callable(unit['convert']): | |
res = unit['convert'](value) | |
else: | |
res = value * unit['convert'] | |
res = '%.2f' % round(res, 2) | |
messages.append((start, '%s %s = %s %s' % (value, name, res, unit['result']))) | |
messages = sorted(messages, key=lambda m: m[0]) | |
return '\n'.join([i[1] for i in messages]) | |
print(convert('1kg 1g 1km 1m 1ft 1yd 1lb 1mi 1f 1C 1acre')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment