Input 检查程序中的错误
我正在尝试对python中的字典计数器进行一些更改。我想对当前计数器进行一些更改,但到目前为止没有任何进展。我希望我的代码显示不同单词的数量 这就是我到目前为止所做的:Input 检查程序中的错误,input,counter,Input,Counter,我正在尝试对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 p
# 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
对于第一个qs,您可以使用
set
来帮助您计算不同单词的数量。(假设每两个单词之间有一个空格)
对于第二个Q,使用字典帮助您记录单词计数是可以的。首先,您的第一个问题是,为单词计数添加一个变量,为不同的单词添加一个变量。所以
wordCount=0
和differentWords=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)
由于您使用的是dictionary,因此不需要使用单独的变量来计算字数,要计算总字数,只需添加键的值(这些值只是计数)您可以使用collections lib中的count函数:
from collections import Counter
q = Counter(fileSource.read().split())
total = sum(q.values())
非常感谢。你能写一个完整的答案吗?我会接受的?我刚刚开始学习python。我应该在哪里添加str='apple boy cat dog elephant fox'不同的\u word\u count=len(set(str.split(“”))?不要更改有问题的代码。现在你什么都没有了。没错,这就是为什么它被否决了?我投票结束这个问题,因为这是一个工作要求
from collections import Counter
q = Counter(fileSource.read().split())
total = sum(q.values())