[英]How to make an array of words from a file?
我想創建一個函數來讀取文本文件中的單詞,然后將它們存儲在一個數組中。
例如,如果文本文件說: "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
中的所有單詞。 您可以執行雙重 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.