Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何创建具有.txt文件的1d列表,该文件已\n?_Python_List - Fatal编程技术网

Python 如何创建具有.txt文件的1d列表,该文件已\n?

Python 如何创建具有.txt文件的1d列表,该文件已\n?,python,list,Python,List,我想读入一个文本文件,并将文件中的每个元素放入一个列表中,而不是为文件中的每一行创建一个单独的列表。例如,如果文件是: 你好,我的名字 是乔吗 我希望名单是[你好,我叫乔]而不是 你好,我叫乔 这是我到目前为止所拥有的 def evaluate_essay(): fileList= [] file= open("text1.txt", "r") fileList= [line.rstrip() for line in file]

我想读入一个文本文件,并将文件中的每个元素放入一个列表中,而不是为文件中的每一行创建一个单独的列表。例如,如果文件是:

你好,我的名字

是乔吗

我希望名单是[你好,我叫乔]而不是

你好,我叫乔

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

 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)

只需读取整个文件并在空白处拆分:

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

您可以使用双for循环来拆分单词,阅读列表理解中的行:

def evaluate_essay():
        with open("text1.txt", "r") as f:
            words = [w for l in f for w in l.split()]

非常感谢你!这是更快的方法。您的示例所需的输出
[您好,我的名字是Joe]
不是有效的Python表达式。你是什么意思?