简体   繁体   English

如何从文件中制作一组单词?

[英]How to make an array of words from a file?

I would like to create a function that reads the words in a text file, and then stores them in an array.我想创建一个函数来读取文本文件中的单词,然后将它们存储在一个数组中。

For example, if the text file said: "John eats eats peas"例如,如果文本文件说: "John eats eats peas"

The result array would look like [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)

My question: How do I store the words into an array and print?我的问题:如何将单词存储到数组中并打印?

Have you tried to append the word in your list array ?您是否尝试在列表array附加单词?

Basically, you have to initialize an empty list.基本上,您必须初始化一个空列表。 In your case you called it array .在您的情况下,您将其称为array Your words contains all the words you want in your final array .您的words包含您想要在最终array中的所有单词。 You can do a double for loop to retrieve them and store them via the append.您可以执行双重 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM