自动组织分类的库

2024-04-29 02:47:32 发布

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

我对项目列表有以下分类法:

例如:

Item 1['taxonomy'] = 'toys/starwars/yoda/Baby Yoda toy'
Item 2['taxonomy'] = 'toys/starwars/yoda/Baby Yoda toy 10inches'
Item 3['taxonomy'] = 'toys/starwars/luke/Luke Skywalker toy'
Item 4['taxonomy'] = 'cloths/starwars/luke/Luke Skywalker toy'

我想自动创建一个分类法“对象”,其表示形式如下

|_ toys (3)
|     |_
|       starwars (3)
|              |_ yoda
|              |_ luke
|                 ...
|_ cloths (1)
               ...

我是否必须手动执行此操作,或者是否有任何库/对象执行此操作? 谢谢

我不一定想要一棵树!我想组织我的分类法并了解分类法行为(了解它对所有文章的结构有多好)

如果没有最后一个分支,如何打印树


Tags: 项目对象itembabytaxonomy分类法yodatoy
1条回答
网友
1楼 · 发布于 2024-04-29 02:47:32

似乎您想要创建一棵树。 可以用anytree表示数据

from anytree import Node, RenderTree

def parse_taxonomy_path(tx, nodes):
    l = s.split('/')

    parent = l[0]
    nodes[parent] = Node(parent, parent=nodes['root'])
    
    for i in range(1,len(l)):
        name = l[i]
        nodes[name] = Node(name, parent=nodes[parent])
        parent = name
    
    return nodes
    
root = Node('root')
nodes = {'root':root}

nodes = parse_taxonomy_path('toys/starwars/yoda/Baby Yoda toy', nodes)

for pre, _, node in RenderTree(root):
    print("%s%s" % (pre, node.name))
root
└── toys
    └── starwars
        └── yoda
            └── Baby Yoda toy

相关问题 更多 >