使用Python在文件中读取多于单词的字符串

非洲曼巴舞

我在将一个以上单词的整个字符串存储到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())

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python读取文件替换单词中的字符串

使用文件名读取最新文件包含python中的字符串

在python中读取.tsv文件时忽略字符串

在Python中以字符串形式读取gz文件

Python读取和搜索文件中的字符串

python字符串作为Skimage中的文件被读取

在python中读取以特定字符串开头的文件

Python 字符串不在文件中读取

使用python regex从字符串中捕获单词

使用python的字符串中单词的加权计数

使用 Python 删除字符串中相邻的重复单词?

使用python将字符串中的某些单词大写

使用字典更改字符串中的单词。Python

如何从.INI文件中读取字符串,然后从文本文件中读取该字符串,并使用Python打印整行?

不使用字符串从文件中读取

读取.txt文件并将单词/整数作为字符串

python,从目录中读取文件名,在bash脚本中使用字符串

使用 Python Flask 从字符串变量中读取并上传 .txt 文件?

使用TCL从文件读取字符串后从字符串中删除空格

读取文件到字符串(python)

从文件中读取字符串

使用goutte读取文件/字符串

每个'if'读取字符串中的每个单词

读取单词并打印所有子字符串,在Python中按长度排序

如何使用python中的预定义单词组将字符串的单词分组为不同的字符串?

使用python获取列表中的单词字符串中的单词计数

如何在python中使用后面的单词检索字符串中的单词?

使用python regex从字符串获取单词,但不在html标签中获取单词

使用 python spacy 从字符串中删除单词而不影响单词