2 回答
TA贡献1757条经验 获得超7个赞
不用将源代码视为字符串,而是使用ast模块来解析源代码,然后遍历各个节点:
import ast
from collections import Counter
tree = ast.parse('''
"""
Author: Nobody
"""
def foo(*args, **kwargs):
for i in range(10):
if i != 2**2:
print(i * 2 * 3 * 2)
def bar():
pass
''')
counts = Counter(node.__class__ for node in ast.walk(tree))
print('The docstring says:', repr(ast.get_docstring(tree)))
print('You have', counts[ast.Mult], 'multiplication signs.')
print('You have', counts[ast.FunctionDef], 'function definitions.')
print('You have', counts[ast.If], 'if statements.')
它非常简单,可以处理所有极端情况:
The docstring says: 'Author: Nobody'
You have 3 multiplication signs.
You have 2 function definitions.
You have 1 if statements.
添加回答
举报