我想在Python源代码中找到一个列表理解,为此我尝试使用Pygments,但它没有找到实现这一点的方法。
更具体地说,我想做一个识别所有可能的列表理解的函数。例如:
[x**2 for x in range(5)]
[x for x in vec if x >= 0]
[num for elem in vec for num in elem]
[str(round(pi, i)) for i in range(1, 6)]
此示例来自 https://docs.python.org/2/tutorial/datastructs.html#list-com 海伦斯
使用正则表达式也是有效的解决方案。
谢谢你
ast
库将 Python 代码解析为语法树,然后遍历解析树来查找 ListComp
表达式。
这是一个简单的示例,它打印在通过 stdin 传递的 Python 代码中找到列表推导式的行号:
import ast
import sys
prog = ast.parse(sys.stdin.read())
listComps = (node for node in ast.walk(prog) if type(node) is ast.ListComp)
for comp in listComps:
print "List comprehension at line %d" % comp.lineno
ast
内置模块。
import ast
my_code = """
print("Hello")
y = [x ** 2 for x in xrange(30)]
"""
module = ast.parse(my_code)
for node in ast.walk(module):
if type(node) == ast.ListComp:
print(node.lineno) # 3
print(node.col_offset) # 5
print(node.elt) # <_ast.BinOp object at 0x0000000002326EF0>
一个简单的解决方案是使用搜索对话框来查找正则表达式。我使用的正则表达式如下:
(\=|\s|\=\s|\()\[.+for.+in.+\]
这将找到列表推导式和生成器。对于您提供的示例,我将表达式修改如下:
\[.+for.+in.+\]
但是,第一个表达式更加完整,因为列表推导式和生成器被分配给变量。