gpt4 book ai didi

nlp - Spacy中的依存解析树

转载 作者:行者123 更新时间:2023-12-01 16:52:57 26 4
gpt4 key购买 nike

我有一句话约翰在商店看到一顶华丽的帽子
如何将其表示为如下所示的依赖树?

(S
(NP (NNP John))
(VP
(VBD saw)
(NP (DT a) (JJ flashy) (NN hat))
(PP (IN at) (NP (DT the) (NN store)))))

我从 here 得到了这个脚本

import spacy
from nltk import Tree
en_nlp = spacy.load('en')

doc = en_nlp("John saw a flashy hat at the store")

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_


[to_nltk_tree(sent.root).pretty_print() for sent in doc.sents]

我收到以下内容,但我正在寻找树(NLTK)格式。

     saw                 
____|_______________
| | at
| | |
| hat store
| ___|____ |
John a flashy the

最佳答案

要为 SpaCy 依赖项解析重新创建 NLTK 样式树,请尝试使用 draw方法来自nltk.tree而不是pretty_print :

import spacy
from nltk.tree import Tree

spacy_nlp = spacy.load("en")

def nltk_spacy_tree(sent):
"""
Visualize the SpaCy dependency tree with nltk.tree
"""
doc = spacy_nlp(sent)
def token_format(token):
return "_".join([token.orth_, token.tag_, token.dep_])

def to_nltk_tree(node):
if node.n_lefts + node.n_rights > 0:
return Tree(token_format(node),
[to_nltk_tree(child)
for child in node.children]
)
else:
return token_format(node)

tree = [to_nltk_tree(sent.root) for sent in doc.sents]
# The first item in the list is the full tree
tree[0].draw()

请注意,由于 SpaCy 目前仅支持单词和名词短语级别的依存解析和标记,因此 SpaCy 树的结构不会像您从斯坦福解析器(例如斯坦福解析器)中获得的那样深入。也可以可视化为一棵树:

from nltk.tree import Tree
from nltk.parse.stanford import StanfordParser

# Note: Download Stanford jar dependencies first
# See https://stackoverflow.com/questions/13883277/stanford-parser-and-nltk
stanford_parser = StanfordParser(
model_path="edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz"
)

def nltk_stanford_tree(sent):
"""
Visualize the Stanford dependency tree with nltk.tree
"""
parse = stanford_parser.raw_parse(sent)
tree = list(parse)
# The first item in the list is the full tree
tree[0].draw()

现在,如果我们同时运行两者,nltk_spacy_tree("John saw a flashy hat at the store.")将产生this imagenltk_stanford_tree("John saw a flashy hat at the store.")将产生this one .

关于nlp - Spacy中的依存解析树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com