【发布时间】:2017-11-26 14:19:31
【问题描述】:
我有一个包含大约 600,000 条 Wikidata 分类记录的大型 RDF 文件。从这个文件中,我只对 subclassOf 关系(谓词)感兴趣,因此,我忽略了仅保留“subclassOf”语句的所有其他语句。声明如下:
ais a subclassOfb,
bis a subclassOfc
就像c 是b 的父级,b 是a 的父级。任何父母都可以有很多孩子。我想使用此分类法构建分层树。
我检查了这个线程,它几乎解决了我的问题。
Recursively creating a tree hierarchy without using class/object
但是,有了这个,我得到了字典中的树,我想将其转换为树数据结构。以下是我尝试过的:
data = [['a','x'], ['b','x'], ['c','x'], ['x','y'], ['t','y'], ['y','p'], ['p','q']]
roots = set()
mapping = {}
for child,parent in data:
childitem = mapping.get(child,None)
if childitem is None:
childitem = {}
mapping[child] = childitem
else:
roots.discard(child)
parentitem = mapping.get(parent,None)
if parentitem is None:
mapping[parent] = {child:childitem}
roots.add(parent)
else:
parentitem[child] = childitem
for root in roots:
print(mapping[root])
tree = { id : mapping[id] for id in roots }
print(tree)
树的输出如下:
{'q': {'p': {'y': {'t': {}, 'x': {'c': {}, 'b': {}, 'a': {}}}}}}
我想将此字典转换为树。所以例如当我说 print(mapping['y']) 时,它应该给我 Node y 即
q
├── p
└── y
目前,如果我说映射['y'],它会给我以 y 为根的子树。我认为对此有一些简单的解决方案,但我无法理解。我也找到了此链接https://gist.github.com/hrldcpr/2012250 将字典转换为树,但不确定如何在我的情况下使用它。或者,如果有人知道直接从我上面给出的 RDF 数据构建树,那么它将是最受欢迎的。可能 python 的anytree API 会解决我的问题。
【问题讨论】:
-
你需要一个“树”类吗?一种为您现在拥有的字典树漂亮地打印节点祖先的方法?还是两者兼而有之?
-
最终我只需要祖先(或到该节点的路径)。无论我是使用树还是字典来获取它都无关紧要。因此,如果我能以某种方式访问嵌套字典中键的路径,我的问题将得到解决。
标签: python dictionary tree rdf taxonomy