基于缩进的语法>AST

2024-06-07 07:02:46 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我想重新发明CoffeeScript:)或Python。或手写笔,或YAML:) 我需要一些工具,它将我的缩进基本语法转换成抽象语法树。不幸的是,谷歌对[基于缩进的sytntax to AST]一无所知。你们知道这样的工具吗? 更具体地说,我所拥有的

===source===
Lorem ipsum:
    dolor sit amet:
        consectetuer adipiscing elit
    sed diam nonummy
nibh euismod tincidunt:
    ut laoreet dolore

…我需要的是:

^{pr2}$

如果你能推荐一些这样的工具,那就太好了。如果这个工具是用python/javascript编写的,并将结果显示为JSON,那就太棒了。 如果你能给我一个关于如何自己创造这个梦想工具的建议,那也很酷:) 谢谢!在


Tags: 工具toyamlsource语法astcoffeescriptipsum
1条回答
网友
1楼 · 发布于 2024-06-07 07:02:46

用递归自己写这个很简单。这里有一个创建list的程序,我将把dict版本留给您作为练习。在

import sys
import re

def DentArthurDent(fp, dents = 0, nextline = None):
    '''Read from FP until EOF or an exdent
       Return dict and next line'''

    tree = []
    while True:
        line, nextline = nextline or fp.readline(), None
        if not line:
            return tree, ''
        parts = re.match(r'(^ *)(.*)', line).group(1,2)
        dent = len(parts[0])
        if dent == dents:
            tree.append(parts[1])
        elif dent > dents:
            child_tree, nextline = DentArthurDent(fp, dent, line)
            tree.append(child_tree)
        else:
            return tree,line


import json
tree, _ = DentArthurDent(sys.stdin)
print json.dumps(tree, indent=4)

此输入:

^{pr2}$

产生以下输出:

[
    "line 1", 
    "line 2", 
    [
        "line 3", 
        [
            "line 4", 
            "line 5"
        ], 
        "line 6"
    ]
]

相关问题 更多 >