我正在尝试计算另一个py文件中的关键字数量,这是我的意思:
import keyword
infile=open(xx.py,'r')
contentbyword=infile.read().split()
num_of_keywords=0
for word in contentbyword:
if keyword.iskeyword(word) or keyword.iskeyword(word.replace(':','')):
num_of_keywords+=1
我知道这是错误的,即使关键字位于引号内或#号之后,它也很重要。
那么,在python中计算橙色突出显示的单词(默认为IDLE)的更好方法是什么?非常感谢<(_ _)>
正确的方法是使用令牌化模块,该模块可处理所有边缘情况。
import token
import keyword
import tokenize
s = open('hi.py').readline
counter = 0
l = []
for i in tokenize.generate_tokens(s):
if i.type == token.NAME and keyword.iskeyword(i.string):
counter += 1
l.append(i.string)
print(counter)
print(l)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句