美化打印PyParsing树
有没有人用Python自带的pprint
模块实现过漂亮的打印功能?最好是能对从PyParsing输出的解析树进行缩进和对齐的那种。
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的时候遇到错误,只需要为特定的数据类型添加一个额外的处理器就可以了。