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)関数の中で、各wordのancestorsを反復処理し、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
____