我试图读取代码文件并计算if语句的数量。我将如何使用AST进行此操作。
答案 0 :(得分:5)
Python具有标准的库ast
:
# assume you are reading Python source
import ast
with open('src.py') as f:
src = f.read()
tree = ast.parse(src)
cnt_if = sum([x for x in ast.walk(tree) if isinstance(x, ast.If)])