依赖解析可视化
Dependency parsing visualisation
如何表示下面的句子:
txt1="The chef cooks the soup"
如下:
我想像图像中显示的那样形象化句子,即 tree/network。
任何建议将不胜感激。我正在使用 nltk 进行词嵌入。
你要找的是NLP中的依赖解析。解析树可以由多个库生成,例如您显示的图像来自斯坦福 NLP,您可以在上面找到大量教程。对于我的大部分 NLP,我更喜欢 Spacy,所以这里有一个 Spacy 方法来做同样的事情。
#!pip install -U spacy
#!python -m spacy download en
from nltk import Tree
import spacy
en_nlp = spacy.load('en')
def tok_format(tok):
return "_".join([tok.orth_, tok.tag_, tok.dep_])
def to_nltk_tree(node):
if node.n_lefts + node.n_rights > 0:
return Tree(tok_format(node), [to_nltk_tree(child) for child in node.children])
else:
return tok_format(node)
command = "The chef cooks the soup"
en_doc = en_nlp(u'' + command)
[to_nltk_tree(sent.root).pretty_print() for sent in en_doc.sents]
cooks_VBZ_ROOT
_____________|_____________
chef_NN_nsubj soup_NN_dobj
| |
The_DT_det the_DT_det
command = "She sells sea shells on the sea shore"
en_doc = en_nlp(u'' + command)
[to_nltk_tree(sent.root).pretty_print() for sent in en_doc.sents]
sells_VBZ_ROOT
______________|_________________________
| | on_IN_prep
| | |
| shells_NNS_dobj shore_NN_pobj
| | ____________|______________
She_PRP_nsubj sea_NN_compound the_DT_det sea_NN_compound
如何表示下面的句子:
txt1="The chef cooks the soup"
如下:
我想像图像中显示的那样形象化句子,即 tree/network。 任何建议将不胜感激。我正在使用 nltk 进行词嵌入。
你要找的是NLP中的依赖解析。解析树可以由多个库生成,例如您显示的图像来自斯坦福 NLP,您可以在上面找到大量教程。对于我的大部分 NLP,我更喜欢 Spacy,所以这里有一个 Spacy 方法来做同样的事情。
#!pip install -U spacy
#!python -m spacy download en
from nltk import Tree
import spacy
en_nlp = spacy.load('en')
def tok_format(tok):
return "_".join([tok.orth_, tok.tag_, tok.dep_])
def to_nltk_tree(node):
if node.n_lefts + node.n_rights > 0:
return Tree(tok_format(node), [to_nltk_tree(child) for child in node.children])
else:
return tok_format(node)
command = "The chef cooks the soup"
en_doc = en_nlp(u'' + command)
[to_nltk_tree(sent.root).pretty_print() for sent in en_doc.sents]
cooks_VBZ_ROOT
_____________|_____________
chef_NN_nsubj soup_NN_dobj
| |
The_DT_det the_DT_det
command = "She sells sea shells on the sea shore"
en_doc = en_nlp(u'' + command)
[to_nltk_tree(sent.root).pretty_print() for sent in en_doc.sents]
sells_VBZ_ROOT
______________|_________________________
| | on_IN_prep
| | |
| shells_NNS_dobj shore_NN_pobj
| | ____________|______________
She_PRP_nsubj sea_NN_compound the_DT_det sea_NN_compound