python - 计数器工作不正常,数一数二
问题描述
我的计数器计算关键字的次数与键入的次数不同。请告诉我有什么问题。
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])
解决方案
该问题已在评论中进行了解释,因此我将仅发布建议的解决方案:
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)
推荐阅读
- javascript - 如何使用 chart.js 添加另一个数据集栏
- asp.net-core - Autofac 会在 netcore 3+ 中支持 IWebHostBuilder API 吗?
- azure-application-insights - Azure 存储队列监控
- python - 在 python 上使用漂亮的汤浏览网站的 HTML
- reactjs - Ant Design - 自动完成不需要显示价值
- selenium - 使用来自 Jenkins 的多个黄瓜标签运行多个功能
- java - Android RecyclerView Java
- python - Pyomo:如何将 None 作为参数值传递
- rust - 如何更改已与另一个流组合的 Tokio 计时器流的持续时间?
- scala - 遍历Scala中的数组