3

pprint有没有人实现了从 PyParsing 输出的解析树的漂亮打印(最好使用 Python 的内置模块),最好是缩进和对齐?

4

1 回答 1

1

您可以为此使用 json。

import json
class PyParseEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, ParseResults):
            x = obj.asDict()
            if x.keys():
                obj = x
            else:
                x = obj.asList()
                if len(x) == 1:
                    obj = x[0]
                else:
                    obj = x 
        else:
            obj = super(PyParseEncoder, self).default(obj)
        return obj

接着

print json.dumps(parseresult, cls=PyParseEncoder, sort_keys=False, indent=2)

如果您从 json.dumps 收到错误,只需为特定数据类型的编码器添加额外的处理程序。

于 2013-06-07T12:23:45.523 回答