我有一个关键词,例如友好。它产生了一个儿童词,例如温暖,同时从父词下降,例如朋友。
from collections import namedtuple
keyword = 'friendly'
childword = 'warm'
parentword = 'friend'
connect=namedtuple(keyword,'children parents')
output = connect([childword],[parentword])
结果,我可以使用output.children来查看我的nodeword的子节点。但是,我真正想要做的是输入
friendly.children # instead of output.children
看孩子们的关键词友好。我怎样才能做到这一点?我是Python的新手;我甚至不确定这是否可行。
答案 0 :(得分:2)
如果要定义树结构,可以使用namedtuple:
from collections import namedtuple
TreeNode = namedtuple('TreeNode', ['word', 'children'])
friend = TreeNode(word='friend', children=[])
friendly = TreeNode(word='friendly', children=[])
warm = TreeNode(word='warm', children=[])
friend.children.append(friendly)
friendly.children.append(warm)
print(friendly.children)
提出:
[TreeNode(word='warm', children=[])]
这是一种非常类似于C的做事方式;你可能最好拥有一个存储边缘关系的Graph或Tree数据结构,例如:
children = dict()
children['friend'] = ['friendly']
children['friendly'] = ['warm']
def parents(word):
ps = []
for k in children:
if word in children[k]:
ps.append(k)
return ps
print(children['friendly'])
print(parents('friendly'))
提出
['warm']
['friendly']
有一篇关于Implementing Graphs in Python的文章,你可能觉得它很有用。