[英]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.