Python - 用字母和数字解析字符串以浮动

时间:2018-04-19 09:15:23

标签: python parsing

我有一个:('56 .5T','181G')我想分开它并解析数字浮动,如果我们将T作为最后一个字符,我想把它转移到gb所以做56.5 * 1024并且结果写入float。如果最后一个字符是G只是解析它。

现在整个结构看起来像这样:

 input = 'HV01': [('c50', '8G', '118G'),
          ('c5d0', '26G', '22.3G')],
         'HV02': [('c5t6005Dd0', '790G', '162G'),
          ('c5t60', '203G', '34.8G'),
          ('c5t6d0', '56.5T', '112G')]

所以它是字典列表中的元组。 我正在做的是在for循环中寻找特定值,如下所示:

for i in dict.keys():
 for j in (dict[i]):
    if j[1] == "*G" || j[2] == "something":
        print ("SOME MOGIC TO HAPPEN")

2 个答案:

答案 0 :(得分:0)

使用已经存在的解析库,专门用于处理这样的案例:humanfriendly

from humanfriendly import parse_size
for s in ["5.6T", "4.9G"]:
    print(parse_size(s) / int(1E9), "G")
# 5600.0 G
# 4.9 G

在您的具体案例中:

from humanfriendly import parse_size, InvalidSize

def parse(x):
    try:
        return parse_size(x) / int(1E9)
    except InvalidSize:
        # anything that is not a size, like the first string
        return x

d = {'HV01': [('c50', '8G', '118G'),
              ('c5d0', '26G', '22.3G')],
     'HV02': [('c5t6005Dd0', '790G', '162G'),
              ('c5t60', '203G', '34.8G'),
              ('c5t6d0', '56.5T', '112G')]}

for values in d.values():
    for line in values:
        print(" ".join("{}G".format(parse(x)) for x in line))
# c50 8.0G 118.0G
# c5d0 26.0G 22.3G
# c5t6005Dd0 790.0G 162.0G
# c5t60 203.0G 34.8G
# c5t6d0 56500.0G 112.0G

如果您想使用二进制前缀而不是十进制前缀,请使用2**30代替int(1E9)

答案 1 :(得分:0)

注意:您无法修改元组的元素。因此,如果我将元组元素(具有T)作为列表,那么将List更改为T的问题可以解决如下:

G

如果您打印import re s = {'HV01': [['c50', '8G', '118G'],['c5d0', '26G', '22.3G']], 'HV02': [['c5t6005Dd0', '790G', '162G'],['c5t60', '203G', '34.8G'],['c5t6d0', '56.5T', '112G']]} k = s.keys() v = s.values() for i in range(len(s)): for j in range(len(v[i])): for k in range(len(v[i][j])): if 'T' in v[i][j][k]: res = re.sub("T","G",v[i][j][k]) v[i][j][k] = str(float(res.split('G')[0]) * 1024 elif 'G' in v[i][j][k]: res = v[i][j][k] res = re.sub("G","T",v[i][j][k]) v[i][j][k] = float(res.split('T')[0]) else : pass print s ,则输出为:

s

TB中的值更改为GB,GB中的值保持原样,没有{'HV02': [['c5t6005Dd0', 790.0, 162.0], ['c5t60', 203.0, 34.8], ['c5t6d0', '57856.0', 112.0]], 'HV01': [['c50', 8.0, 118.0], ['c5d0', 26.0, 22.3]]} T扩展名。