2017-06-01 68 views
1

我需要使用Python转换人类可读的上传大小限制(例如100kb,32MB等)。转换后的值应该表示为字节数。用单位(100kb,32MB)将大小符号转换为Python中的字节数

convert_size_to_bytes("32MB") # should return 33554432 
convert_size_to_bytes("100kB") # should return 102400 
convert_size_to_bytes("123B") # should return 123 
convert_size_to_bytes("123") # should return 123 

回答

3

下面的函数工作:

def convert_size_to_bytes(size): 
    multipliers = { 
     'kb': 1024, 
     'mb': 1024*1024, 
     'gb': 1024*1024*1024, 
     'tb': 1024*1024*1024*1024 
    } 

    for suffix in multipliers: 
     if size.lower().endswith(suffix): 
      return int(size[0:-len(suffix)]) * multipliers[suffix] 
    else: 
     if size.lower().endswith('b'): 
      return int(size[0:-1]) 

    try: 
     return int(size) 
    except ValueError: # for example "1024x" 
     print('Malformed input!') 
     exit() 

print(convert_size_to_bytes("32MB")) 
print(convert_size_to_bytes("100kB")) 
print(convert_size_to_bytes("123B")) 
print(convert_size_to_bytes("123")) 

您可以测试这个功能在这里:http://ideone.com/kse773

此功能需要改进,以支持单个字符大小单位(例如B字节)。由于BkB不同的方法应该通过应用的后缀。使用

+2

这是这些罕见的情况之一,''for'循环上的'else'对捕获单个'b'有意义。 –

+1

@ Ev.Kounis感谢您确认'for'循环中的'else'在这里是可以接受的。我纠正了我的答案。 – Robson

+2

为了让它充分证明,你可能想封装'try'块中的最后一个'return',如:[this](http://ideone.com/BMDb0V) –

3

备选的正则表达式和替换功能:

import re 

suffixes = "","k","m","g","t" 
multipliers = {'{}b'.format(l) : 1024**i for i,l in enumerate(suffixes) } 

sre = re.compile("(\d+)({})".format("|".join(x+"b" for x in suffixes)),re.IGNORECASE) 

def subfunc(m): 
    return str(int(m.group(1))*multipliers[m.group(2).lower()]) 

def convert_size_to_bytes(size): 
    return sre.sub(subfunc,size) 


print(convert_size_to_bytes("32MB")) 
print(convert_size_to_bytes("100kB")) 
print(convert_size_to_bytes("123")) 

的字典和正则表达式根据所述单元生成的(所以它可以扩展到EXA,地图...)

当匹配数字+单位,它将第一组的计算整数乘以字典的值来替换表达式),并将其转换回字符串,如re.sub函数所需。

相关问题