计算文件中 if 语句的数量

Count the number of if statements in a file

我正在尝试读取代码文件并计算 if 语句的数量。我怎样才能使用 AST 来做到这一点。

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)])