首页 > 解决方案 > 计数器工作不正常,数一数二

问题描述

我的计数器计算关键字的次数与键入的次数不同。请告诉我有什么问题。

Input: while while
output: while: 1
phrase = input('Enter Python source code:').split(' ')
counter = 0
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:
        dict1[x] = counter
        if x in dict1:
            dict1[x] += 1
        else:
            dict1[x]=1

sorted_dict= dict(sorted(dict1.items()))
for x in sorted_dict:
    print(x,':',dict1[x])

标签: python

解决方案


该问题已在评论中进行了解释,因此我将仅发布建议的解决方案:

from collections import Counter
from keyword import kwlist


keywords = set(kwlist)
phrase = input('Enter Python source code: ').split()
d = Counter(word for word in phrase if word in keywords)

推荐阅读