统计每个关键字和每个标识符的出现次数

Counting the occurrence of each keyword and each identifier

我试图计算问题给我的单词中的关键字和标识符,但我不确定是否正确,所以请帮助我找出我在问题中提出的问题。 问题是这样的:

编写一个程序,读取 Python 源代码文件并使用两个字典计算文件中每个关键字和每个标识符(变量,class 和方法名称)的出现次数:一个一个用于关键字,一个用于标识符。您的程序应提示用户输入 Python 源代码文件名。 Python 编程语言中的关键字:False class finally is return None continue for l ambda try True def from nonlocal while and del global not or yield assert else import pass break except与 elif 中的一样 raise

Python编程语言中的关键字:

False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise

这是我写的代码:

import tokenize
import keyword
import collections 
with open('source.py') as f:
    tokens = (token for _, token, _, _, _ in tokenize.generate_tokens(f.readline))
    c = collections.Counter(token for token in tokens if keyword.iskeyword(token))

print(c)

回应您的评论,从技术上讲,c 不是字典,它是一个 collections.Counter 对象:

print(c, type(c))

输出:

Counter({'False': 1, 'True': 1}) <class 'collections.Counter'>

您可以像这样将其转换为内置字典:

c = dict(c)
print(c, type(c))

输出:

{'False': 1, 'True': 1} <class 'dict'>

如您所见,它摆脱了 Counter() 对象。

它不是很漂亮,但如果你只知道应该有两个词典,那么第二位是最正确的。

但是再次阅读你的问题看起来你需要为 (1): 关键字(你已经提供)和 (2 ) 标识符:标识符是给予实体的名称,例如 class、函数、变量等。它有助于将一个实体与另一个实体区分开来。您能否提供您的 python 文件:source.py?