我想创建一个函数,该函数读取文本文件中的单词,然后将它们存储在数组中。
例如,如果文本文件说:"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)
我的问题:如何将单词存储到数组中并打印?
您是否尝试过将单词附加到列表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)