【问题标题】:Any good or better or direct way to get the chunking result from a nltk Tree?从 nltk 树中获取分块结果的任何好的或更好的或直接的方法?
【发布时间】:2019-02-06 00:51:55
【问题描述】:

我想对字符串进行分块以使组处于特定高度。应保留原始顺序,并且还应完整包含所有原始单词。

import nltk 
height = 2
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]

pattern = """NP: {<DT>?<JJ>*<NN>}
VBD: {<VBD>}
IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern) 
result = NPChunker.parse(sentence)

In [29]: Tree.fromstring(str(result)).pretty_print()
                             S                                      
            _________________|_____________________________          
           NP                        VBD       IN          NP       
   ________|_________________         |        |      _____|____     
the/DT little/JJ yellow/JJ dog/NN barked/VBD at/IN the/DT     cat/NN

我的方法有点像下面这样的蛮力:

In [30]: [list(map(lambda x: x[0], _tree.leaves())) for _tree in result.subtrees(lambda x: x.height()==height)]
Out[30]: [['the', 'little', 'yellow', 'dog'], ['barked'], ['at'], ['the', 'cat']]

我认为应该存在一些直接的 API 或者我可以用来进行分块的东西。任何建议都受到高度赞赏。

【问题讨论】:

  • 不。但只需致电Tree.leaves() 并检查Tree.height。你做对了 =)
  • @alvas 没关系。但我不明白你提到这两种方法的意思。以及某人的反对票。 :)
  • 不是我 ;P
  • @alvas 我认为保持字符串不仅不重叠和分组而且保持完整和原始顺序会更好。
  • 那么你不仅想要 Tree 对象的叶子,还想要 Tree 或 str 的叶子?目前尚不清楚目的是什么。你能再提供几个输入/输出吗?

标签: python nlp nltk depth-first-search chunking


【解决方案1】:

不,NLTK 中没有任何内置函数可以返回特定深度的树。

但是你可以使用来自How to Traverse an NLTK Tree object?的深度优先遍历

为了提高效率,您可以先进行深度迭代,并且仅在深度小于必要时才重复,例如

import nltk 
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]

pattern = """NP: {<DT>?<JJ>*<NN>}
VBD: {<VBD>}
IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern) 
result = NPChunker.parse(sentence)

def traverse_tree(tree, depth=float('inf')):
    """ 
    Traversing the Tree depth-first,
    yield leaves up to `depth` level.
    """
    for subtree in tree:
        if type(subtree) == nltk.tree.Tree:
            if subtree.height() <= depth:
                yield subtree.leaves()
                traverse_tree(subtree)


list(traverse_tree(result, 2))

[出]:

[[('the', 'DT'), ('little', 'JJ'), ('yellow', 'JJ'), ('dog', 'NN')],
 [('barked', 'VBD')],
 [('at', 'IN')],
 [('the', 'DT'), ('cat', 'NN')]]

另一个例子:

x = """(S
  (NP the/DT 
      (AP little/JJ yellow/JJ)
       dog/NN)
  (VBD barked/VBD)
  (IN at/IN)
  (NP the/DT cat/NN))"""

list(traverse_tree(Tree.fromstring(x), 2))

[出]:

[['barked/VBD'], ['at/IN'], ['the/DT', 'cat/NN']]

【讨论】:

    猜你喜欢
    • 2016-08-05
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    相关资源
    最近更新 更多