简体   繁体   English

解析名词短语列表中的 NLTK 树输出

[英]Parse NLTK tree output in a list of noun phrase

I have a sentence我有一句话

text  = '''If you're in construction or need to pass fire inspection, or just want fire resistant materials for peace of mind, this is the one to use. Check out 3rd party sellers as well Skylite'''

I applied NLTK chunking on it and getting a tree as output.我在它上面应用了 NLTK 分块并得到一棵树作为输出。

sentences = nltk.sent_tokenize(d)
sentences = [nltk.word_tokenize(sent) for sent in sentences]
sentences = [nltk.pos_tag(sent) for sent in sentences]

grammar = """NP: {<DT>?<JJ>*<NN.*>+}
       RELATION: {<V.*>}
                 {<DT>?<JJ>*<NN.*>+}
       ENTITY: {<NN.*>}"""

cp = nltk.RegexpParser(grammar)
for i in sentences:
    result = cp.parse(i)
    print(result)
    print(type(result))
    result.draw() 

Output is as follows:输出如下:

(S If/IN you/PRP (RELATION 're/VBP) in/IN (NP construction/NN) or/CC (NP need/NN) to/TO (RELATION pass/VB) (NP fire/NN inspection/NN) ,/, or/CC just/RB (RELATION want/VB) (NP fire/NN) (NP resistant/JJ materials/NNS) for/IN (NP peace/NN) of/IN (NP mind/NN) ,/, this/DT (RELATION is/VBZ) (NP the/DT one/NN) to/TO (RELATION use/VB) ./.)

HOw can I get noun phrase in format of list of a strings:如何以字符串列表的格式获取名词短语:

[construction, need, fire inspection, fire, resistant materials, peace, mind, the one]

Some suggestions please......?请给一些建议......?

Something like this:像这样的东西:

noun_phrases_list = [[' '.join(leaf[0] for leaf in tree.leaves()) 
                      for tree in cp.parse(sent).subtrees() 
                      if tree.label()=='NP'] 
                      for sent in sentences]
#[['construction', 'need', 'fire inspection', 'fire', 'resistant materials', 
#  'peace', 'mind', 'the one'], 
# ['party sellers', 'Skylite']]

can use filter on subtrees like below可以在子树上使用过滤器,如下所示

grammar = "NP: {<DT>?<JJ>*<NN>}"
cp = nltk.RegexpParser(grammar)
result = cp.parse(sentences[1])
result.subtrees(filter =lambda t: t.label() == 'NP') # gives you generator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM