繁体   English   中英

Python,人类可读的字节转换

[英]Python, Human Readable to Byte Conversion

我试图在 python 中将人类可读的形式转换为字节。 我认为字节为人类可读的形式,但我无法反其道而行之。

我尝试了 stackowerflow 中的一些代码,但它无法完美运行,或者我找不到正确的代码。

@staticmethod
def byte_to_human_read(byte):
    if byte == 0:
        raise ValueError("Size is not valid.")
    byte = int(byte)
    size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    index = int(math.floor(math.log(byte, 1024)))
    power = math.pow(1024, index)
    size = round(byte / power, 2)
    return "{} {}".format(size, size_name[index])

@staticmethod
def human_read_to_byte(size):
    - I need here - 

我需要 def human_read_to_byte(size) 函数。

示例:输入 -> 1 GB 输出 -> 1,073,741,824(以字节为单位)

所以你已经有了一个尺寸列表,对吧? 做同样的事情,但方向相反:

def human_read_to_byte(size):
    size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    size = size.split()                # divide '1 GB' into ['1', 'GB']
    num, unit = int(size[0]), size[1] 
    idx = size_name.index(unit)        # index in list of sizes determines power to raise it to
    factor = 1024 ** idx               # ** is the "exponent" operator - you can use it instead of math.pow()
    return num * factor

当然,您需要在其中构建一些错误处理,但这相当简单 - 您已经为byte_to_human_read()做了一些。

您可以使用如下方法。 字典用于保存数字因子转换的缩写。 虽然字符串解析不是防弹的,但它可以处理输入中的多个空格或没有空格以及小写字符。

CONVERSION_FACTORS = { "B": 1, "KB":1024, "MB":1048576, "GB": 1073741824, "TB": 1099511627776, "PB": 1125899906842624, "EB":1152921504606846976 , "ZB": 1180591620717411303424, "YB": 1208925819614629174706176}
def human_read_to_byte(size):
    num_ndx = 0
    while num_ndx < len(size):
        if str.isdigit(size[num_ndx]):
            num_ndx += 1
        else:
            break
    num_part = int(size[:num_ndx])
    str_part = size[num_ndx:].strip().upper()
    return num_part * CONVERSION_FACTORS[str_part]

正如对@green-cloak-guy 的回答的评论所说,您可能需要float()而不是int() 如果是这种情况,解析会稍微复杂一些。

由于这些问题和答案,我想出了一个简短的代码,可以使用拆分 (1 B) 和紧密 (10KB) 格式。 小心,代码在某些情况下可能很脆弱,我的输入非常严格。

def human_read_to_byte(size):
  factors = {'B': 1, 'KB':1024, 'MB':1048576, 'GB': 1073741824, 'TB': 1099511627776, 'PB': 1125899906842624, 'EB':1152921504606846976 , 'ZB': 1180591620717411303424, 'YB': 1208925819614629174706176}
  if size[-2:] in factors:
    return factors[size[-2:]]*float(size[:-2])
  return float(size[:-1])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM