gpt4 book ai didi

python - 如何从文件中创建单词数组?

转载 作者:行者123 更新时间:2023-12-01 00:19:40 25 4
gpt4 key购买 nike

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

例如,如果文本文件显示:“John eats eatspeas”

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

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

最佳答案

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

基本上,您必须初始化一个空列表。在您的例子中,您将其称为数组。您的words 包含您想要在最终数组 中包含的所有单词。您可以执行双 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)

关于python - 如何从文件中创建单词数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59042164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com