簡體   English   中英

Python NLTK解析子樹

[英]python NLTK parse subtree

關於NLTK中樹木的兩個問題:

  1. 我可以在一棵樹(句子)中區分第一,第二,...子樹嗎?
  2. 如何使用子樹葉子中的標簽?

以下代碼效果很好,

          for subtree in tree.subtrees(filter=lambda t: t.node == 'NP'):
            for attributes in subtree.leaves():
                print attributes

但它返回帶有單詞和標簽的列表:

('noun', 'NN')
('verb', VBZ)

依此類推:我需要區分子樹中不同類型的單詞。 subtree.labels()不存在。

就像是:

           for subtree in tree.subtrees(filter=lambda t: t.node == 'NP'):
            for attributes in subtree.leaves():
                if subtree.labels() == 'NN':
                  # do something with the nouns...

謝謝你的提示

所以我用python做到了。 無論如何,如果有人有更好的主意...

         for subtree in tree.subtrees(filter=lambda t: t.node == 'NP' or t.node == 'NNS'):
            for attributes in subtree.leaves():
                (expression, tag) = attributes
                if tag == 'NN':
                    # do something with the nouns

我做了以下類似的事情,從樹中提取名詞短語。

from itertools import groupby
[' '.join([t[0] for t,m in group]) for key, group in groupby(tree.pos(), lambda s: s[-1]=='NP') if key]

更籠統地說,我們可以檢查“組”內部的內容,並對組中的元素進行任何操作。 例如,

[list(group]) for key, group in groupby(tree.pos(), lambda s: s[-1]=='NP') if key]

一旦知道了“列表(組)”中的元素所包含的內容,我們就可以對其進行任何操作。

另一種方法是使用tree2conlltags。 例如,

from nltk.chunk import tree2conlltags
from itertools import groupby

chunks = tree2conlltags(tree)

print(chunks)

results = [' '.join(word for word, pos, chunk in group).lower() for key, group in groupby(chunks, lambda s: s[-1]!='O') if key]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM