Python关键字计数器统计异常求助:重复输入关键字未正确计数
Fixing Your Python Keyword Counter's Counting Bug
Let's break down what's going wrong with your keyword counter and fix it up step by step.
The Root of the Problem
Looking at your loop logic, there are two critical issues throwing off the count:
- You’re using a
countervariable that’s unnecessary and actively breaking the count. Every time you match a keyword, you first setdict1[x] = counter(which is always 0), then increment it to 1. Even if the keyword appears multiple times, this overwrites the existing count back to 0 before adding 1—so you’ll never get a number higher than 1. - Your conditional check after setting
dict1[x] = counteris redundant because you just added the key to the dictionary, so theelseblock will never run.
Fixed Code
Here’s the corrected version of your script, with clear explanations of the changes:
phrase = input('Enter Python source code:').split(' ') keywords = {"and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try"} dict1 = {} for x in phrase: if x in keywords: # Use dict.get() to safely get the current count (0 if not present) and increment by 1 dict1[x] = dict1.get(x, 0) + 1 # Sort the dictionary alphabetically by keyword sorted_dict = dict(sorted(dict1.items())) # Clean up the print loop by unpacking key-value pairs for keyword, count in sorted_dict.items(): print(f"{keyword}: {count}")
Key Improvements
- Removed the useless
countervariable—we don’t need it because we’re tracking counts directly in the dictionary. - Used
dict.get(x, 0)to handle both cases (keyword seen before or not) in one line: if the keyword is already indict1, we get its current count; if not, we default to 0. Then we add 1 to that value. - Simplified the final print loop by unpacking key-value pairs directly, making the code cleaner and easier to read.
Testing this with input while while will now correctly output while: 2 as expected.
内容的提问来源于stack exchange,提问作者Nevin Abraham
相关产品推荐
相关产品推荐

