Python库,用于轻松显示树形结构
项目描述
树打印机
============
此库提供了一种树打印机类,用于轻松显示树形结构
## 安装
``` sh
$ pip install treeprinter
```
## 基本用法
### 打印机实例
``` python
from treeprinter import TreePrinter
class Tree(object)
def __init__(self, tag, children=None)
self.children = children or []
self.tag = tag
tree = Tree("animal", [
Tree("cat"),
Tree("dog", [Tree("chihuahua"), Tree("dalmatian")]),
Tree("wolf")])
printer = TreePrinter('children', 'tag')
printer.pprint(tree)
```
```
animal
|
---------------------------
| | |
cat dog wolf
|
----------
| |
chihuahua dalmatian
```
### 打印机装饰器
您也可以通过如下装饰器来实现类,从而实现\_\_str\_\_方法,以获得相同的结果
``` python
@TreePrinter('children', 'tag')
class Tree(object)
def __init__(self, tag, children=None)
self.children = children or []
self.tag = tag
print(tree)
```
## 扩展
您可以通过实现基本显示器来扩展此库
(见printers/json_printer.py)
``` python
from treeprinter import JsonPrinter
printer = JsonPrinter()
json = {
"fruits": ["Apple", "Banana", "Pear"],
"presidents": {
"France": ["Sarkozy", "Hollande"],
"USA": ["Trump", "Obama"]
},
"star": "Sun"
}
printer.pprint(json)
```
```
{}
|
--------------------------------------
| | |
{presidents} [fruits] star
| | |
---------------- -------------- Sun
| | | | |
[France] [USA] Apple Banana Pear
| |
--------- ------
| | | |
Sarkozy Hollande Trump Obama
```
============
此库提供了一种树打印机类,用于轻松显示树形结构
## 安装
``` sh
$ pip install treeprinter
```
## 基本用法
### 打印机实例
``` python
from treeprinter import TreePrinter
class Tree(object)
def __init__(self, tag, children=None)
self.children = children or []
self.tag = tag
tree = Tree("animal", [
Tree("cat"),
Tree("dog", [Tree("chihuahua"), Tree("dalmatian")]),
Tree("wolf")])
printer = TreePrinter('children', 'tag')
printer.pprint(tree)
```
```
animal
|
---------------------------
| | |
cat dog wolf
|
----------
| |
chihuahua dalmatian
```
### 打印机装饰器
您也可以通过如下装饰器来实现类,从而实现\_\_str\_\_方法,以获得相同的结果
``` python
@TreePrinter('children', 'tag')
class Tree(object)
def __init__(self, tag, children=None)
self.children = children or []
self.tag = tag
print(tree)
```
## 扩展
您可以通过实现基本显示器来扩展此库
(见printers/json_printer.py)
``` python
from treeprinter import JsonPrinter
printer = JsonPrinter()
json = {
"fruits": ["Apple", "Banana", "Pear"],
"presidents": {
"France": ["Sarkozy", "Hollande"],
"USA": ["Trump", "Obama"]
},
"star": "Sun"
}
printer.pprint(json)
```
```
{}
|
--------------------------------------
| | |
{presidents} [fruits] star
| | |
---------------- -------------- Sun
| | | | |
[France] [USA] Apple Banana Pear
| |
--------- ------
| | | |
Sarkozy Hollande Trump Obama
```
项目详情
关闭
treeprinter-0.0.2.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 28c80ab15176ad79a64c9a87641fbe25bc991628bc722f8934ba845b74a422c3 |
|
MD5 | 09a1dbe1285f1b254424c68bc9513b43 |
|
BLAKE2b-256 | 23acaf9d2a7e6f21923ffed0d3d9377dbdb1af4ff5b60fc95451046778767826 |