繁体   English   中英

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

[英]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.

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