如何在Python / Jupyter Notebook中漂亮地打印或可视化类'CoreNLP_pb2.ParseTree'的对象?

问题描述

我在Jupyter笔记本中使用Stanza的CoreNLP客户端对字符串进行选区分析。最终输出以类“ CoreNLP_pb2.ParseTree”的对象的形式出现。

>>> print type(result)
<class 'CoreNLP_pb2.ParseTree'>

我应该如何以可见方式打印?当我直接致电print(result)时,没有输出

解决方法

您可以将CoreNLP_pb2.ParseTree转换为nltk.tree.Tree,然后调用pretty_print()转换为以可见方式打印解析树。

from nltk.tree import Tree
def convert_parse_tree_to_nltk_tree(parse_tree):
    return Tree(parse_tree.value,[get_nltk_tree(child) for child in parse_tree.child]) if parse_tree.child else parse_tree.value

convert_parse_tree_to_nltk_tree(constituency_parse).pretty_print()

结果如下:

                      ROOT                    
                       |                       
                       S                      
        _______________|____________________   
       |                    VP              | 
       |            ________|___            |  
       NP          |            NP          | 
   ____|_____      |    ________|_____      |  
 NNP        NNP   VBZ  DT       JJ    NN    .
  |          |     |   |        |     |     |  
Chris     Manning  is  a       nice person  .