mer*_*rpi 6 python list-comprehension pygments
我想在 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)]
Run Code Online (Sandbox Code Playgroud)
这个例子是从https://docs.python.org/2/tutorial/datastructs.html#list-comspirations获得的
使用正则表达式也是有效的解决方案。
谢谢
您可以使用该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
Run Code Online (Sandbox Code Playgroud)
您可以使用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>
Run Code Online (Sandbox Code Playgroud)