我如何在Python中使用此信息?我不知道如何使用这种数据类型

时间:2009-12-13 11:40:05

标签: python list variables types tuples

根据NLTK的书,我首先应用语法,并解析它。

grammar = r"""
            NP: {<DT|PP\$>?<JJ>*<NN>}
                {<NNP>+}
                """
cp = nltk.RegexpParser(grammar)
chunked_sent =  cp.parse(sentence)

当我打印chunked_sent 时,我明白了:

(S
  i/PRP
  use/VBP
  to/TO
  work/VB
  with/IN
  you/PRP
  at/IN
  (NP match/NN)
  ./.)

我不想只看它。我想真正拿出“NP”名词短语。

如何打印出“匹配”...这是名词短语? 我希望从那个chunked_sent中获得所有“NP”。

for k in chunked_sents:
    print k

(u'i', 'PRP')
(u'use', 'VBP')
(u'to', 'TO')
(u'work', 'VB')
(u'with', 'IN')
(u'you', 'PRP')
(u'at', 'IN')
(NP match/NN)
(u'.', '.')


for k in chunked_sents:
    print k[0]

i
use
to
work
with
you
at
(u'match', 'NN')

由于某种原因,我看到我失去了“NP” 另外,如何确定k [0]是字符串还是元组(如上例所示)

1 个答案:

答案 0 :(得分:0)

你可能已经找到了答案。我是为将来可能面临这种情况的人发布的。

for subtree in chunked_sent.subtrees():
    if subtree.node == 'NP': print subtree