如何从文件中排列单词数组?

问题描述 投票:0回答:1

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

例如,如果文本文件说:"John eats eats peas"

结果数组看起来像[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)

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

python arrays list pygame text-files
1个回答
0
投票

您是否尝试过将单词附加到列表array中?

基本上,您必须初始化一个空列表。在您的情况下,您将其称为array。您的words包含您最终array中想要的所有单词。您可以执行double for循环来检索它们并通过追加将其存储。

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)
© www.soinside.com 2019 - 2024. All rights reserved.