forked from microsoft/ai4eutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ai4e_string_utils.py
53 lines (45 loc) · 1.21 KB
/
ai4e_string_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
Miscellaneous string utilities.
"""
import re
def is_float(s):
"""
Checks whether a string represents a valid float
"""
try:
_ = float(s)
except ValueError:
return False
return True
def human_readable_to_bytes(size):
"""
Given a human-readable byte string (e.g. 2G, 10GB, 30MB, 20KB),
return the number of bytes. Will return 0 if the argument has
unexpected form.
https://gist.github.com/beugley/ccd69945346759eb6142272a6d69b4e0
"""
size = re.sub(r'\s+', '', size)
if (size[-1] == 'B'):
size = size[:-1]
if (size.isdigit()):
bytes = int(size)
elif (is_float(size)):
bytes = float(size)
else:
bytes = size[:-1]
unit = size[-1]
try:
bytes = float(bytes)
if (unit == 'T'):
bytes *= 1024*1024*1024*1024
elif (unit == 'G'):
bytes *= 1024*1024*1024
elif (unit == 'M'):
bytes *= 1024*1024
elif (unit == 'K'):
bytes *= 1024
else:
bytes = 0
except ValueError:
bytes = 0
return bytes