gpt4 book ai didi

python - 使用Python读取文件中包含多个单词的字符串

转载 作者:行者123 更新时间:2023-12-01 06:49:32 26 4
gpt4 key购买 nike

我在将包含多个单词的整个字符串存储到 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', ...]

这也会影响年份列表,因为如果它有多个单词,它会从专业停止处开始。有谁知道这个问题的解决方法或者我做错了什么?

最佳答案

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

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())

关于python - 使用Python读取文件中包含多个单词的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59081897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com