【发布时间】:2016-11-22 09:21:35
【问题描述】:
我正在做一个 nlp 项目,我想根据它在依赖关系树中的位置过滤掉单词。
为了绘制树,我使用了来自 post 的代码:
def to_nltk_tree(node):
if node.n_lefts + node.n_rights > 0:
return Tree(node.orth_, [to_nltk_tree(child) for child in node.children])
else:
return node.orth_
对于一个例句:
“世界各地的一群人突然在精神上联系在一起”
我得到了这棵树:
我想从这棵树中得到一个元组列表,其中包含单词及其在树中的相应深度:
[(linked,1),(are,2),(suddenly,2),(mentally,2),(group,2),(A,3),(of,3),(people,4)....]
对于这种情况,我对没有孩子的单词不感兴趣:[are,suddenly,mentally,A,the] 所以到目前为止我所能做的就是只获取有孩子的单词列表,所以我使用这个代码:
def get_words(root,words):
children = list(root.children)
for child in children:
if list(child.children):
words.append(child)
get_words(child,words)
return list(set(words)
[to_nltk_tree(sent.root).pretty_print() for sent in doc.sents]
s_root = list(doc.sents)[0].root
words = []
words.append(s_root)
words = get_words(s_root,words)
words
[around, linked, world, of, people, group]
从这里我怎样才能得到所需的带有单词及其各自深度的元组?
【问题讨论】:
标签: python tree nlp nltk spacy