始める無料で始める

spaCy のパーサーを使ったロールの割り当て

この演習では、spaCy の強力な構文パーサーを使って、ユーザーのメッセージに含まれるエンティティにロールを割り当てます。そのために、find_parent_item()assign_colors() という2つの関数を定義します。動画でAlanが示したように、解析木(パースツリー)を使ってロールを割り当てましょう。

単語の祖先ノードには、.ancestors 属性を使ってアクセスできます。

この演習はコースの一部です

Python でチャットボットを作る

コースを見る

演習の手順

  • メッセージ "let's see that jacket in red and some blue jeans"nlp オブジェクトに渡し、doc という名前の spacy ドキュメントを作成しましょう。
  • find_parent_item(word) 関数の中で、各 wordancestors を反復処理し、entity_type()"item" になるものを見つけましょう。
  • assign_colors(doc) 関数の中で、doc を反復処理して entity_type"color" の単語を見つけ、その word の親アイテムを特定しましょう。
  • spacy ドキュメントを assign_colors() 関数に渡しましょう。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Create the document
doc = ____

# Iterate over parents in parse tree until an item entity is found
def find_parent_item(word):
    # Iterate over the word's ancestors
    for parent in ____:
        # Check for an "item" entity
        if entity_type(____) == "____":
            return parent.text
    return None

# For all color entities, find their parent item
def assign_colors(doc):
    # Iterate over the document
    for word in ____:
        # Check for "color" entities
        if entity_type(word) == "____":
            # Find the parent
            item =  ____
            print("item: {0} has color : {1}".format(item, word))

# Assign the colors
____ 
コードを編集して実行