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
Isjohn(\n)eats(\n)eats(\n)peas
a字符串或列表?请编辑此答案以解释它如何解决OP的问题。