处理从文本文件读取的列表时Python中的错误

时间:2017-07-05 11:21:44

标签: python list split

这是我的代码。我是Python的新手:

    f=open('dt2.txt','r').read().split('\n')
    for i in range (len(f)):
        a=f[i].split('\t')
        print type(a)
        print str(a[1])," with roll no: ",str(a[0])," ",
        c=0
        d=0
        for j in range (0,100):
            try:
                if str(a[j])=="HU101":
                    c+=1
                if str(a[j])=="HU301":
                    c+=1
                if str(a[j])=="HU481":
                    c+=1
                if str(a[j])=="HU501":
                    c+=1
                if str(a[j])=="HU601":
                    c+=1
                if str(a[j])=="HU781":
                    c+=1
                if str(a[j])=="HU801A":
                    c+=1
                if str(a[j])=="HU801B":
                    c+=1
                if str(a[j])=="M101":
                    d+=1
            except IndexError:
                continue
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"

我收到此错误:

enter image description here

2 个答案:

答案 0 :(得分:1)

让我们看看我是否可以提供帮助......在python中,csv-library和... open被认为更“pythonic”。 with ... open确保文件在打开后正确关闭。

import csv
with open('dt2.txt') as f:
    mydata = [i for i in csv.reader(f, delimiter='\t')] # one-liner

另一个提示......您还可以通过以下方式大幅缩短代码:

if str(a[j]) in ["HU101","HU301",...,"HU801B"]:
   c+=1

答案 1 :(得分:0)

坦率地说,这段代码太可怕了。如果我理解你正在努力实现的目标,那么这是一种更清洁的方式:

f = open('dt2.txt','r') 
for line in f:
    a = line.split('\t')
    print "{} with roll no: {} ".format(a[1],a[0]),
    c = sum(1 for j in a if j in set("HU101", "HU301", "HU481", "HU501", "HU601", "HU781", "HU801A", "HU801B"))
    d = 1 if "M101" in a else 0
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"
f.close()