2014-02-06 122 views
0
dic = dict() 
with open('C:\\Users\\aman\\Documents\\dataVal.txt', 'r') as fh: 
    for l in fh.readlines(): 
     try: 
      lines = l.split() 
      date, sub, num = lines[0], lines[1], [int(x) for x in lines[2:]] 
      dic.setdefault(date, {}) 
      dic[date][sub] = num 
     except Exception as er: 
      print er 
print dic 

有人可以帮忙吗? 它给我一个错误,说无效文字为int()与基地10:'16:00:00'。如何摆脱它?只为您的信息'16:00:00' 是在表中的第一列中的TXT文件无效文字为int()以10为底:'16:00:00'

16:00:00  Maths 100 95 65 32 23 45 77 54 78 88 45 67 89 
17:00:00 Science 45 53 76 78 54 78 34 99 55 100 45 56 78 
18:00:00 English 43 45 56 76 98 34 65 34 45 67 76 34 98 
+0

请竖起你解析线和错误。顺便说一句,如果你也是字符串类型,请将int(x)更改为str(x)。 –

+0

以及你想要的输出? 'time as key' –

+0

你可以粘贴你的错误,'16:00:00'可以用作字符串,所以你的代码应该可以工作 –

回答

1

我改变INT(X),以STR(X),请你试试。如果那是错误。

dic = dict() 
with open('C:\\Users\\aman\\Documents\\dataVal.txt', 'r') as fh: 
    for l in fh.readlines(): 
     try: 
      lines = l.split() 
      date, sub, num = lines[0], lines[1], [str(x) for x in lines[2:]] 
      dic.setdefault(date, {}) 
      dic[date][sub] = num 
     except Exception as er: 
      print er 
print dic 

输出:

{'17:00:00': {'Science': ['45', '53', '76', '78', '54', '78', '34', '99', '55', '100', '45', '56', '78']}, 
    '18:00:00': {'English': ['43', '45', '56', '76', '98', '34', '65', '34', '45', '67', '76', '34', '98']}, 
    '16:00:00': {'Maths': ['100', '95', '65', '32', '23', '45', '77', '54', '78', '88', '45', '67', '89']}} 
+0

请把错误 –

+0

啊对不起,我改变了'try'的缩进和'except'现在检查 –

+0

这个作品很完美。谢啦 – sam

相关问题