检查我的程序中的错误

Checking errors in my program

我正在尝试对 python 中的字典计数器进行一些更改。我想对当前的计数器进行一些更改,但到目前为止没有取得任何进展。我希望我的代码显示不同单词的数量。

这是我目前拥有的:

# import sys module in order to access command line arguments later
import sys


# create an empty dictionary
dicWordCount = {}

# read all words from the file and put them into 
#'dicWordCount' one by one,
# then count the occurance of each word

对于你的第一个问题,你可以使用set来帮助你计算不同单词的数量。 (假设每两个单词之间有一个space)

str = 'apple boy cat dog elephant fox'
different_word_count = len(set(str.split(' '))) 

你的第二个问题,用字典帮你记录word_count就可以了

首先,您的第一个问题,为字数添加一个变量,为不同的字添加一个变量。所以 wordCount = 0differentWords = 0。在您的文件读取循环中,将 wordCount += 1 放在顶部,并在您的第一个 if 语句中将 differentWords += 1 放在顶部。您也可以在程序结束时打印出这些变量。

第二个问题,在你的打印中,添加if语句,if len(strKey)>4:

如果您想要完整的示例代码,请点击此处。

import sys

fileSource = open(sys.argv[1], "rt")
dicWordCount = {}
wordCount = 0
differentWords = 0

for strWord in fileSource.read().split():
  wordCount += 1
  if strWord not in dicWordCount:
    dicWordCount[strWord] = 1
    differentWords += 1
  else:
    dicWordCount[strWord] += 1

for strKey in sorted(dicWordCount, key=dicWordCount.get, reverse=True):
  if len(strKey) > 4: # if the words length is greater than four.
    print(strKey, dicWordCount[strKey])
print("Total words: %s\nDifferent Words: %s" % (wordCount, differentWords))

这个怎么样?

#gives unique words count
unique_words = len(dicWordCount)


total_words = 0
for k, v in dicWordCount.items():
    total_words += v

#gives total word count
print(total_words)

你不需要一个单独的变量来计算字数,因为你使用的是字典,要计算总字数,你只需要添加键的值(这只是计数)

您可以使用集合库中的计数函数:

from collections import Counter
q = Counter(fileSource.read().split())
total = sum(q.values())