【问题标题】:Reading strings with more than word in a file using Python使用 Python 读取文件中多个单词的字符串
【发布时间】:2020-03-23 16:48:03
【问题描述】:

我在将包含多个单词的整个字符串存储到 Python 列表中时遇到问题。给定一个包含学生信息的文件,例如名字、姓氏、专业和他们的年份,看起来像这样:

Terrence Jones    Computer Science    Freshman
Amy Johnson       Biology             Freshman
Craig Anderson    Criminal Justice    Sophomore

等等..

我的目标是创建一个将这些属性存储到列表中的程序。名字和姓氏都有效,但是当我进入某些专业比其他专业长的专业时,我遇到了问题。这是我尝试使用的代码:

def main():
    survey = open("survey.txt", "r")
    lines = survey.readlines()

    firstNames = [] # list that stores first names of students that filled out survey
    lastNames = [] # list that stores last names of students that filled out survey
    major = [] # list that stores the major of students that filled out survey
    year = [] # list that stores the classification year of students that filled out survey

    for count in lines:
        # stores the information from file into the attributes for students
        firstNames.append(count.split(' ')[0])
        lastNames.append(count.split(' ')[1])
        major.append(count.split()[2])
        year.append(count.split()[3])

这是我打印专业列表时的输出:

['Computer', 'Biology', 'Criminal', ...]

我期待一个会显示的输出

['Computer Science', 'Biology', 'Criminal Justice', ...]

这也影响了年份列表,因为如果它超过一个单词,它会从专业停止的地方开始。有没有人碰巧知道解决这个问题或我做错了什么?

【问题讨论】:

    标签: python string list file


    【解决方案1】:

    不要指望空格的数量。反而;根据列宽对线进行切片:

    0.................18..................38
    Terrence Jones    Computer Science    Freshman
    

    例如:

    for line in lines:
        full_name = line[:18].strip()
        firstNames.append(full_name.split(" ")[0])
        lastNames.append(full_name.split(" ")[1])
        major.append(line[18:38].strip())
        year.append(line[38:].strip())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多