3 回答
TA贡献1982条经验 获得超2个赞
我们有类似的需求,为此我创建了asttokens库。它以文本和标记化形式维护源,并用标记信息标记AST节点,从中也可以轻松获得文本。
它适用于Python 2和3(经过2.7和3.5测试)。例如:
import ast, asttokens
st='''
def greet(a):
say("hello") if a else say("bye")
'''
atok = asttokens.ASTTokens(st, parse=True)
for node in ast.walk(atok.tree):
if hasattr(node, 'lineno'):
print atok.get_text_range(node), node.__class__.__name__, atok.get_text(node)
印刷
(1, 50) FunctionDef def greet(a):
say("hello") if a else say("bye")
(17, 50) Expr say("hello") if a else say("bye")
(11, 12) Name a
(17, 50) IfExp say("hello") if a else say("bye")
(33, 34) Name a
(17, 29) Call say("hello")
(40, 50) Call say("bye")
(17, 20) Name say
(21, 28) Str "hello"
(40, 43) Name say
(44, 49) Str "bye"
TA贡献2051条经验 获得超10个赞
ast.get_source_segment 是在python 3.8中添加的:
import ast
code = """
if 1 == 1 and 2 == 2 and 3 == 3:
test = 1
"""
node = ast.parse(code)
ast.get_source_segment(code, node.body[0])
产生: if 1 == 1 and 2 == 2 and 3 == 3:\n test = 1
添加回答
举报