Skip to main content
 首页 » 编程设计

Python NLTK : Extract lexical head item from Stanford dependency parsed result

2025年05月04日15oomusou

我有一个句子,我想提取词首项,我可以使用斯坦福 NLP 库进行依存分析。

如何提取句子中的主要中心词?

在句子下载并共享此工具的情况下,头部将是下载。

我试过以下方法:

 def get_head_word(text): 
     standepparse=StanfordDependencyParser(path_to_jar='/home/stanford_resource/stanford-parser-full-2014-06-16/stanford-parser.jar',path_to_models_jar='/home/stanford_resource/stanford-parser-full-2014-06-16/stanford-parser-3.4-models.jar',model_path='/home/stanford_resource/stanford-parser-full-2014-06-16/stanford-parser-3.4-models/edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz') 
     parsetree=standepparse.raw_parse(text) 
     p_tree=list(parsetree)[0] 
     print p_tree.to_dot() 
 
 text = 'Download and share this tool' 
 get_head_word(text) 
 
 
output: 
 
digraph G{ 
edge [dir=forward] 
node [shape=plaintext] 
 
0 [label="0 (None)"] 
0 -> 1 [label="root"] 
1 [label="1 (Download)"] 
1 -> 2 [label="cc"] 
1 -> 3 [label="conj"] 
1 -> 5 [label="dobj"] 
2 [label="2 (and)"] 
3 [label="3 (share)"] 
4 [label="4 (this)"] 
5 [label="5 (software)"] 
5 -> 4 [label="det"] 
} 

请您参考如下方法:

要找到句子的依赖中心,只需查找其head 值指向root 节点的节点。在 NLTK API 中为 DependencyGraph ,你可以很容易地找到它的头指向字典第一个索引的节点。

请注意,与典型的乔姆斯基范式/CFG 解析树不同,在依赖解析中,依赖解析可能有不止一个头。

但是由于您要将依赖项输出转换为树结构,因此您可以执行以下操作:

tree_head = next(n for n in p_tree.node_values() if n['head'] == 1) 

但请注意,从语言上讲,Download and share this tool这句话的中心词应该是Download and share。但在计算上,树是分层的,正常形式的树将具有 ROOT->Download->and->share 但某些解析器也可能生成此树:ROOT->and->Download ;分享