【问题标题】:creating a function that reads a file, stores in array, then prints the number of times the words appear in the array创建一个读取文件,存储在数组中,然后打印单词出现在数组中的次数的函数
【发布时间】:2019-11-26 02:30:16
【问题描述】:

我想创建一个函数;

  • 读取文本文件,逐字读取文件并将单词存储在数组中。

  • 计算每个单词出现的次数,并且每个单词只在数组中存储一次。

  • 输出每个单词,旁边显示其出现次数。

示例:

文本文件说:“弗兰克吃豌豆吃薯条豌豆”

将创建一个数组,[Frank, eats, peas, eats, fries, peas]

然后,将打印最终产品;

弗兰克 1 吃 2 豌豆 2 薯条 1

--

这就是我目前所拥有的

def countWordsInFile():
    array = []
    array2 = [1,2,3,4,5]
    length = len(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():
        array.append(words)
    print(array)

    for i in range(0,length,1):
        count = array.count[i]
        array2.append(count)
    print(array2)

【问题讨论】:

    标签: python arrays list text-files


    【解决方案1】:

    您可以为此使用字典,您修改后的代码如下所示:

    def countWordsInFile():
        words = {}
        fileName = getUserText("Enter the name of the file you want to read array from")
        openFile = openNewFile(fileName,"read")
        for word in openFile.read().split():
            if word not in words:
                words[word] = 1
            else:
                words[word] += 1
        print(words)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      相关资源
      最近更新 更多