2017-09-27 5 views
1

文法でカバーされていない単語のリストをプログラムに返す方法を教えてください。 とValueError:「『ミシェル』、 『バナナ』」:文法は、入力単語の一部をカバーしていない、それだけでエラーメッセージが表示されCFG文法のレキシコンに含まれていない単語を取得するにはどうすればよいですか?

import nltk 
    # Define the cfg grammar. 
    grammar = nltk.CFG.fromstring(""" 
    S -> NP VP 
    VP -> V NP 
    NP -> det N | N 
    V -> "eats" | "drinks" 
    N -> "President" | "apple" 
    det -> "The" | "a" | "an" 
    """) 
    sentence = "The President Michel eats banana" 

    # Load the grammar into the ChartParser. 
    cp = nltk.ChartParser(grammar) 

    # Generate and print the parse from the grammar given the sentence tokens. 
    for tree in cp.parse(sentence.split()): 
     print(tree) 

:たとえば、以下のコードを検討してください。

しかし、私は文法でカバーされていないこれらの言葉を、プログラムのどこかで使用することを望みます。

答えて

1

grammar.check_coverage(sentence.split())を使用することもできますが、欠落している単語のリストで同じ例外が発生します。しかし、check_coverage方法のソースを見て:

def check_coverage(self, tokens): 
    """ 
    Check whether the grammar rules cover the given list of tokens. 
    If not, then raise an exception. 

    :type tokens: list(str) 
    """ 
    missing = [tok for tok in tokens 
       if not self._lexical_index.get(tok)] 
    if missing: 
     missing = ', '.join('%r' % (w,) for w in missing) 
     raise ValueError("Grammar does not cover some of the " 
         "input words: %r." % missing) 

あなたが好きな自分の一例に基づいて新しい関数を書くことができます:

def get_missing_words(grammar, tokens): 
    """ 
    Find list of missing tokens not covered by grammar 
    """ 
    missing = [tok for tok in tokens 
       if not grammar._lexical_index.get(tok)] 
    return missing 

とあなたの例では['Michel', 'banana']を取得するためにget_missing_words(grammar, sentence.split())のように使用します。

関連する問題