Python代码问题:误将高频单词识别为最长单词
report_stat Hey there! Let's fix that bug in your report_stat function right away. The issue is clear: you're currently grabbing the most frequent word instead of the longest one, and it all boils down to one line of code.
What Went Wrong
This line is the root cause:
max_word = max(word_dict, key = word_dict.get)
When you use key=word_dict.get, Python uses the value of each dictionary entry (the word's occurrence count) to find the maximum. That's why you're getting "the"—it's the most common word in your text, not the longest by character length.
Corrected Function
Here's the fixed version, with the critical change highlighted:
def report_stat(word_dict): # Changed key to len() to compare word lengths, not occurrence counts max_word = max(word_dict, key=len) 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.txt 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)
Extra: Handling Ties for Longest Word
If your text has multiple words with the same maximum length (like "antidisestablishmentarianism" and "floccinaucinihilipilification"), the above code will only return the first one it encounters. To list all longest words instead, replace the longest word section with this:
# Calculate the maximum word length first max_length = max(len(word) for word in word_dict) # Collect all words that match this length longest_words = [word for word in word_dict if len(word) == max_length] # Print all longest words print('Longest word(s) are:', ', '.join(longest_words))
This way, you won't miss any words that share the title of longest.
Test It Out
With this fix, running your code on pride.txt will now output the actual longest word in the text (like "unhappiness" or another lengthy term) instead of "the".
内容的提问来源于stack exchange,提问作者user9750292

