我正在从文本文件中读取位置记录,例如,它如下所示:

AB ATEA 000401550

每个记录都分配了特定数量的字符,例如:
Code: AB (characters from 0 - 2)
Name: ATEA (characters from 3 - 7)
Value1: 00040 (characters from 8 - 13)
Value2: 1550 (characters from 13 - 16)

我可以使用循环和元组列表作为记录键和字符位置对其进行解析,并将这些记录存储在字典中:
   alist = [('Code',0,2),('Name',3,7),('Value1',8,13),('Value2',13,16)]
   adict = {}
   for x in afile:
      for a, b, c in alist:
         adict[a] = x[b:c]

现在,问题是字典值必须使用特定的数据类型和特定的小数位数进行格式化,例如:
Code = X i.e. string
Name = X i.e. string
Value1 = 9V9(4) i.e. float with 4 decimals, i.e. 0.0040
Value2 = 9(2)V9(2) i.e. float with 2 decimals, i.e. 15.50

所以,我想我可以构建一个函数,它以记录名称和记录值作为输入,然后,在这个函数中有一个包含记录值格式的字典,例如:
    def converter(name, value):
        adict = {'Code':'%s' % value,
                 'Name':'%s' % value,
                 'Value1':float('%s.%s' % (value[:1],value[1:])),
                 'Value2':float('%s.%s' % (value[:2],value[2:]))}
        return adict[name]

问题是,当我按如下方式运行解析循环时:
   alist = [('Code',0,2),('Name',3,7),('Value1',8,13),('Value2',13,16)]
   adict = {}
   for x in afile:
      for a, b, c in alist:
         adict[a] = converter(a,x[b:c])

python抛出value error,因为函数中的值输入在运行时通过字典中的所有项传递,因此,当'ab'被传递到“float()”时,字典创建将停止,python抛出错误。

最佳答案

可以为每个项指定转换器:

def float_converter(value):
    return float('{0}.{1}'.format(value[:1], value[1:]))

alist = [('Code'  , 0 , 2 , None),
         ('Name'  , 3 , 7 , None),
         ('Value1', 8 , 13, float_converter),
         ('Value2', 13, 16, float_converter)]

adict = {}
for x in afile:
   for name, start, stop, converter in alist:
      value = x[start:stop]
      if converter:
          value = converter(value)
      adict[name] = value

在线查看工作:ideone

关于python - 迭代字符串格式/解析?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8435676/

10-10 00:58
查看更多