You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python源码关键字统计程序计数器无法正确统计重复关键字求助

Python关键字统计程序问题修复

错误原因

  • 核心错误:对输入分割后的结果使用set()去重,直接丢失了重复关键字的计数依据,这是输入两个while仅统计到1次的根本原因。
  • 分割逻辑缺陷:按单个空格split(' ')的分割方式鲁棒性差,若输入存在多个连续空格、关键字旁带标点/括号等符号时,无法正确识别关键字。
  • 冗余逻辑:初始化计数字典时循环反复调用fromkeys重写字典,属于无效执行代码。
  • 输出逻辑不符合要求:计数过程中逐次打印,没有按需求最终统一按关键字升序输出结果。

修复后代码

import re

# 读取输入
phrase = input('Enter Python source code:')
# 用正则提取所有符合Python标识符规则的单词,自动过滤符号、空格干扰
words = re.findall(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b', phrase)

# 自定义关键字集合,也可以用标准库keyword.kwlist替代无需手动维护
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"}

# 初始化计数字典,所有关键字初始计数为0
count_dict = {kw: 0 for kw in keywords}
# 遍历计数
for word in words:
    if word in count_dict:
        count_dict[word] += 1
# 按关键字升序输出出现过的关键字及计数
for kw in sorted(count_dict.keys()):
    if count_dict[kw] > 0:
        print(f"{kw}: {count_dict[kw]}")

简化实现方案(使用Counter工具)

import re
from collections import Counter

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"}

phrase = input('Enter Python source code:')
words = re.findall(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b', phrase)
# 仅统计属于关键字的单词
kw_counter = Counter(word for word in words if word in keywords)
# 按升序输出
for kw in sorted(kw_counter.keys()):
    print(f"{kw}: {kw_counter[kw]}")

内容的提问来源于stack exchange,提问作者Nevin Abraham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:51:02