Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的结构模式匹配_Python_Python 3.x_Parsing - Fatal编程技术网

Python中的结构模式匹配

Python中的结构模式匹配,python,python-3.x,parsing,Python,Python 3.x,Parsing,我试图解析一些Python的开源代码,以检查源代码是否包含一些特定的模式 例如: for i in range...: if(i == 2): ....... 我可能想知道源代码是否包含如上所述的模式:for循环中的if语句。我知道表达式模式匹配技术,但它不适用于这种情况 有人知道如何自动找到这种模式匹配吗?有什么有用的工具吗?使用ast.parse() 这个例子非常简单,它只在代码的顶层查找,在第二层查找if。您应该能够将其扩展到搜索嵌套结构的递归解决方案。看看ast模块,它

我试图解析一些Python的开源代码,以检查源代码是否包含一些特定的模式

例如:

for i in range...:
    if(i == 2):
    .......
我可能想知道源代码是否包含如上所述的模式:for循环中的if语句。我知道表达式模式匹配技术,但它不适用于这种情况

有人知道如何自动找到这种模式匹配吗?有什么有用的工具吗?

使用
ast.parse()


这个例子非常简单,它只在代码的顶层查找
,在第二层查找
if
。您应该能够将其扩展到搜索嵌套结构的递归解决方案。

看看
ast
模块,它将解析Python代码并返回其树表示形式。是的,我尝试了ast模块。我可以检测循环的位置,但我无法检测内部有if语句的for循环。
import ast

code = '''
for i in range(1, 10):
    if (i == 2):
        print(i)
'''
parsed = ast.parse(code)
for stmt in parsed.body:
    if isinstance(stmt, ast.For):
        for stmt2 in stmt.body:
            if isinstance(stmt2, ast.If):
                print("Found if in for")
                break