需要输出单词的最大长度

2024-05-16 01:09:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: andthemostlongestiscountercommondict
1条回答
网友
1楼 · 发布于 2024-05-16 01:09:44

如果想要最长的单词,key函数应该使用^{}

max_word = max(word_dict, key=len)

与以下内容相同:

max_word = max(word_dict, key=lambda x: len(x))

您使用max()的方式将按字典顺序给出最后一个单词。你知道吗

相关问题 更多 >