导入文件并将其放入特定格式的元组(python)中

时间:2014-12-02 20:37:06

标签: python list import tuples

我真的被这段代码所困,我已经工作了9个小时,我无法让它工作。基本上我导入一个文件并将其拆分为逐行读取行,其中一个任务是重新排列文件中的行,例如第一行是:34543,2,g5000,Joseph James Collindale应该如下所示: [' Collindale,Joseph James' 34543',g5000',' 2']。所以基本上它应该循环遍历文件中的每一行并重新排列它以使其看起来像上面那种格式。我创建了一个函数来检查行的长度是5还是6,因为它们都有不同的格式。

def tupleT(myLine):
     myLine = myLine.split()
     if len(myLine) == "5":
         tuple1 = (myLine[4],myLine[3],myLine[0],myLine[2],myLine[1])
         return tuple1
     elif len(myLine) == "6":
        tuple1 = (myLine[5],myLine[3]+ myLine[4],myLine[0],myLine[2], myLine[1])
        return tuple1

mylist = [] 
x = input("Enter filename: ")
try :
 f = open(x)
 myLine = f.readline()
 while (len(myLine)>0):
     print(myLine[:-1])
     myLine = f.readline()
     tupleT(myLine)
 f.close()
except IOError as e :
    print("Problem opening file")


This is what the original file looks like in textpad and its called studs.txt:
12345 2 G400 Bart Simpson
12346 1 GH46 Lisa Simpson
12347 2 G401 Homer J Simpson
12348 4 H610 Hermione Grainger
12349 3 G400 Harry Potter
12350 1 G402 Herschel Shmoikel Krustofski
13123 3 G612 Wayne Rooney
13124 2 I100 Alex Ferguson
13125 3 GH4P Manuel Pellegrini
13126 2 G400A Mike T Sanderson
13127 1 G401 Amy Pond
13128 2 G402 Matt Smith
13129 2 G400 River Storm
13130 1 H610 Rose Tyler

1 个答案:

答案 0 :(得分:0)

以下是一些注释代码,可帮助您入门。你的代码有点难读。

考虑重新命名firstsecondthird,因为我不知道它们是什么......

#!/usr/bin/env python

# this is more readable since there are actual names rather than array locations
def order_name(first, second, third, first_name, middle_name, last_name=None):
        if not last_name:
                # if there is no last name we got the last name in middle name (5 arguments)
                last_name = middle_name
        else:
                # if there is a middle name add it to the first name to format as needed
                first_name = "%s %s" % (first_name, middle_name)
        return ("%s, %s" % (last_name, first_name), first, third, second)

with open('studs.txt') as o:
        # this is a more standard way of iterating file rows
        for line in o.readlines():
                # strip line of \n
                line = line.strip()
                print "parsing " + line
                # you can unpack a list to function arguments using the star operator.
                print "ordered: " + str(order_name(*line.split()))