def report_stat(word_dict):
max_word = max(word_dict, key = word_dict.get)
print('Longest word is:', max_word)
# getting sorted list of word dict by value and printing 5 most common
print('Five most common words are:')
counter = 1
for each_list in sorted(word_dict.items(),
key=lambda x: x[1], reverse=True):
# printing the 5 most commonly used words
if counter > 5:
break
print(each_list[0], each_list[1])
counter += 1
# opening the file out.xt in write mode
#and writing word and their count sorted alphabetically
with open('out.txt', 'w') as fp:
for each_word in sorted(word_dict):
print(each_word, word_dict[each_word], file=fp)
我搞错的地方是下面显示的Longest word is: the
。你知道吗
它是印刷最常用的字,而不是最长的字。你知道吗
Enter the filename: pride.txt
Longest word is: the
Five most common words are:
the 4322
to 4126
of 3596
and 3531
her 2181
如果想要最长的单词,key函数应该使用^{} :
与以下内容相同:
您使用
max()
的方式将按字典顺序给出最后一个单词。你知道吗相关问题 更多 >
编程相关推荐