zunit.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import re
  2. multipliers = {
  3. 'b': 1,
  4. 'kb': 1000,
  5. 'mb': 1000*1000,
  6. 'gb': 1000*1000*1000,
  7. 'tb': 1000*1000*1000*1000,
  8. 'pb': 1000*1000*1000*1000*1000,
  9. 'eb': 1000*1000*1000*1000*1000*1000,
  10. 'yb': 1000*1000*1000*1000*1000*1000*1000,
  11. 'kib': 1024,
  12. 'mib': 1024*1024,
  13. 'gib': 1024*1024*1024,
  14. 'tib': 1024*1024*1024*1024,
  15. 'pib': 1024*1024*1024*1024*1024,
  16. 'eib': 1024*1024*1024*1024*1024*1024,
  17. 'yib': 1024*1024*1024*1024*1024*1024*1024,
  18. }
  19. def parseUnitByte(s):
  20. secs = 0.0
  21. items = re.split(r'\s', s)
  22. for item in items:
  23. match = re.match('^(?P<amount>[0-9]+)(?P<unit>.*)$', item)
  24. if not match:
  25. continue # ignore
  26. unit = match.group('unit').lower()
  27. if unit not in multipliers:
  28. continue # ignore
  29. multiplier = multipliers[unit]
  30. secs += float(match.group('amount')) * multiplier
  31. return secs
  32. testcases = [
  33. ( '10b', 10),
  34. ('1kb', 1000),
  35. ('1kb 1b', 1001),
  36. ('1tb 2gb 3mb 4kb 5b', (1000*1000*1000*1000) + (1000*1000*1000*2) + (1000*1000*3) + (1000*4) + 5),
  37. ('1TB 2GB 3MB 4KB 5B', (1000*1000*1000*1000) + (1000*1000*1000*2) + (1000*1000*3) + (1000*4) + 5),
  38. ('', 0),
  39. (' ', 0),
  40. ('2yib', 2361183241434822606848),
  41. ('2kib 4mib', (2*1024) + (4 * 1024*1024) ),
  42. (' 1mb 3b ', (1000*1000) + 3)
  43. ]
  44. if __name__ == '__main__':
  45. for input, output in testcases:
  46. real = parse(input)
  47. if real != output:
  48. print "%r gives %r, not %r" % (input, real, output)
  49. print real
  50. print 'done'