【问题标题】:Reading a text file and assigning the values读取文本文件并分配值
【发布时间】:2016-08-22 16:24:48
【问题描述】:

我有一个包含 5 列的文本文件:

StudentID    UserID    FirstName   LastName   NickName
0122334      7727263   John         Smith      Johnny
8273263      8349734   timmer       Jansen     tim

我正在尝试在 python 中读取此文件并将每个值分配给单独的变量。到目前为止,我已经成功阅读了这些行。但是,我无法分配值。

到目前为止的代码:

StudentID = []
UserID = []
FirstName = []
LastName = []
NickName = []

with open(textfile,'r') as f:
    lines = f.readlines()

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    您可以一次提取所有这些:

    with open(textfile,'r') as f:
        columns = [line.split() for line in f.readlines()]
    

    然后从columns创建每个列表:

    StudentID, UserID, firstNAme, LastNAme, NickName = map(list, zip(*columns))
    

    首先,您创建一个列表列表,该列表是一个由给定列逐行分隔的矩阵。然后它通过为每一列制作一个单独的列表来重新组合(映射)它们。

    【讨论】:

      【解决方案2】:
      f = open(textfile, 'r')
      for line in f:
          student_id, user_id, first_name, last_name, nick_name = line.split(' ')
      StudentId.append(student_id)
      UserId.append(user_id)
      ....
      f.close()
      

      不过,这是一种很奇怪的写法。更好的方法是创建一个 Student 类,该类将知道学生的属性以及如何从行中读取

      class Student:
          def __init__(self, student_id=0, user_id=0, first_name='', last_name='', nickname=''):
              self._student_id = student_id
              self._user_id = user_id
              ...
      
          def from_line(self, line):
              values = line.split(' ')
              self._student_id = int(values[0])
              self._user_id = int(values[1])
              ...
      
      f = open(textfile, 'r')
      students = []
      for line in f:
          students.append(Student())
          students[-1].from_line(line)
      

      【讨论】:

        【解决方案3】:
        with open(textfile,'r') as f:
            for line in f.readlines():
                student_id ,user_id, first_name, last_name, nick_name = line.split()
                StudentID.append(student_id)
                UserID.append(user_id) 
                FirstName.append(first_name) 
                LastName.append(last_name)
                NickName.append(nick_name)
        

        注意:对于列表的命名,您使用的是 Camel 大小写约定。在 Python 中,根据 PIP8 定义变量,您应该使用由下划线 _ 分隔的小写字母。 CamelCase 变量用于定义类。

        建议:

        由于这些值属于同一个对象,您应该按照Dmitry 的建议维护一个对象列表,或者,只需存储list 的列表。

        例如:

        persons = []
        with open(textfile,'r') as f:
            for line in f.readlines():
                persons.append(line.split())
        
        print persons
        # [['0122334', '7727263', 'John', 'Smith', 'Johnny'],
        #  ['8273263', '8349734', 'timmer', 'Jansen', 'tim']]
        

        在这里,您将拥有StudentIDUserIDFirstNameLastNameNickName 012311 @index 分别。

        【讨论】:

        • for item, collection in zip(line.split(),[StudentID, UserID, FirstName, LastName, NickName]):collection.append(item)
        • @Steven:将其添加为答案。这对其他人会有所帮助。
        猜你喜欢
        • 2016-11-02
        • 2016-03-14
        • 1970-01-01
        • 2019-05-29
        • 1970-01-01
        • 1970-01-01
        • 2015-05-25
        • 1970-01-01
        • 2020-11-30
        相关资源
        最近更新 更多