Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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 如何从文件中生成单词数组?_Python_Arrays_List_Pygame_Text Files - Fatal编程技术网

Python 如何从文件中生成单词数组?

Python 如何从文件中生成单词数组?,python,arrays,list,pygame,text-files,Python,Arrays,List,Pygame,Text Files,我想创建一个函数,读取文本文件中的单词,然后将它们存储在数组中 例如,如果文本文件说:“John吃豌豆” 结果数组看起来像[John,eats,eats,peas] def countWordsInFile(): array = [] fileName = getUserText("Enter the name of the file you want to read array from") openFile = openNewFile(fileName,"read")

我想创建一个函数,读取文本文件中的单词,然后将它们存储在数组中

例如,如果文本文件说:
“John吃豌豆”

结果数组看起来像
[John,eats,eats,peas]

def countWordsInFile():
    array = []
    fileName = getUserText("Enter the name of the file you want to read array from")
    openFile = openNewFile(fileName,"read")
    i = openFile
    for words in i.read().split():
        print(words)

我的问题:如何将单词存储到数组中并打印?

您是否尝试将单词附加到列表
数组中

基本上,您必须初始化一个空列表。在您的例子中,您将其称为
array
。 您的
单词
包含最终
数组中所需的所有单词
。您可以执行双for循环来检索它们并通过append存储它们

def countWordsInFile():

    array = []
    fileName = getUserText("Enter the name of the file you want to read array from")
    openFile = openNewFile(fileName,"read")
    i = openFile
    for words in i.read().split():
        for word in words:
            array.append(word)

    print(array)

print(words)
返回什么?打印出上面文件中的所有单词示例,john(\n)eats(\n)eats(\n)peas我想
i.read().split()
就是您要找的。打印一个字符串或列表,而不是
words
Is
john(\n)eats(\n)eats(\n)peas
a字符串或列表?请编辑此答案以解释它如何解决OP的问题。