如何使用具有\ n的.txt创建一维列表? [英] How to create a 1d list with a .txt that has \n?

查看:76
本文介绍了如何使用具有\ n的.txt创建一维列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个文本文件,并将文件的每个元素放入一个列表中,而不是为文件中的每一行都单独列出一个列表.因此,例如,如果文件为:

I want to read in a a text file and put every element of the file into one list instead of having a separate list for every line in the file. So for example, if the file was:

你好我的名字

是乔

我希望列表为[你好,我叫乔],而不是

I want the list to be [Hello my name Is Joe] instead of

[[你好,我的名字] [是乔]]

[[Hello my name] [is Joe]]

这是我到目前为止所拥有的

Here's what I have so far

 def evaluate_essay():
        fileList= []
        file= open("text1.txt", "r")
        fileList= [line.rstrip()  for line in file]
        file.close()
        fileList=[item.split(" ") for item in fileList]
        print (fileList)

推荐答案

只需读取整个文件并在空白处分割即可:

Just read the entire file and split on whitespace:

with open("text1.txt", "r") as f:
    file_list = f.read().split()

这篇关于如何使用具有\ n的.txt创建一维列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆