pythonast转为字典
时间: 2023-07-24 07:32:00 浏览: 111
你可以使用 `ast` 模块将 Python 源代码解析成 AST(抽象语法树)对象,然后将 AST 对象转换为字典。
下面是一个示例代码,可以将 AST 对象转换为字典:
```
import ast
def ast_to_dict(node):
if isinstance(node, ast.AST):
fields = {}
for field, value in ast.iter_fields(node):
fields[field] = ast_to_dict(value)
return {
"type": type(node).__name__,
"fields": fields,
}
elif isinstance(node, list):
return [ast_to_dict(x) for x in node]
else:
return node
```
你可以将你的 Python 源代码解析成 AST 对象,然后将 AST 对象传递给 `ast_to_dict` 函数,该函数将返回一个字典,该字典表示该 AST 对象:
```
source_code = "print('Hello, world!')"
ast_tree = ast.parse(source_code)
ast_dict = ast_to_dict(ast_tree)
print(ast_dict)
```
输出结果应该类似于:
```
{
"type": "Module",
"fields": {
"body": [
{
"type": "Expr",
"fields": {
"value": {
"type": "Call",
"fields": {
"func": {
"type": "Name",
"fields": {
"id": "print",
"ctx": {
"type": "Load"
}
}
},
"args": [
{
"type": "Str",
"fields": {
"s": "Hello, world!"
}
}
],
"keywords": []
}
}
}
}
]
}
}
```
希望这可以帮助到你。
阅读全文