Python and NLTK: How to analyze sentence grammar?

前端 未结 2 2121
长发绾君心
长发绾君心 2020-12-03 19:31

I have this code which should show the syntactic structure of the sentence according to defined grammar. However it is returning an empty []. What am I missing or doing wron

2条回答
  •  無奈伤痛
    2020-12-03 20:17

    You don't have a Det defined in your grammar, but each NP (and consequently S) has to have one by grammar definition.

    Compare with

    >>> grammar = nltk.parse_cfg("""
    ... S -> NP VP
    ... NP -> Det N | Det N PP
    ... VP -> V NP | VP PP
    ... Det -> 'a' | 'the'
    ... N -> 'Kim' | 'Dana' | 'everyone'
    ... V -> 'arrived' | 'left' |'cheered'
    ... """)
    >>>
    >>> parser = nltk.ChartParser(grammar)
    >>> parser.nbest_parse('the Kim left a Dana'.split())
    [Tree('S', [Tree('NP', [Tree('Det', ['the']), Tree('N', ['Kim'])]), Tree('VP', [Tree('V', ['left']), Tree('NP', [Tree('Det', ['a']), Tree('N', ['Dana'])])])])]
    

提交回复
热议问题