Skip to content

Instantly share code, notes, and snippets.

@righ
Created December 28, 2014 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save righ/9b214a3ad57bd1f83051 to your computer and use it in GitHub Desktop.
Save righ/9b214a3ad57bd1f83051 to your computer and use it in GitHub Desktop.
# coding: utf-8
import re
regnum = re.compile(r'([0-9]+)')
def factory(units):
def flat(string):
"""minimize unit"""
string = string.replace(',', '')
result = regnum.search(string.lower())
if result:
try:
num = int(result.group(1))
num *= units.get(string[result.end():], 1)
return num
except ValueError:
pass
return flat
bit = factory({
'b': 1, 'kb': 1024, 'mb': 1024**2, 'gb': 1024**3, 'tb': 1024**4,
'byte': 8, 'kbyte': 1024*8, 'mbyte': 1024**2*8,
'gbyte': 1024**3*8, 'tbyte': 1024**4*8,
})
byte = factory({
'b': 1, 'kb': 1024, 'mb': 1024**2, 'gb': 1024**3, 'tb': 1024**4, 'pb': 1024**5,
})
second = factory({
's': 1, 'm': 60, 'h': 3600, 'd': 3600*24, 'w': 3600*24*7,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment