正規表現によるエンティティ抽出
次は、別のシンプルな手法を使って、"hello, my name is David Copperfield" のような文から人名を見つけてみましょう。
ここでは、"name" や "call(ed)" といったキーワードを探し、正規表現を使って大文字で始まる単語を検出することで、それを人名と判断します。この演習では、find_name() 関数を定義しましょう。
この演習はコースの一部です
Python でチャットボットを作る
演習の手順
re.compile()を使って、"name"または"call"というキーワードが含まれているかチェックするパターンを作成しましょう。- 大文字で始まる単語を検索するパターンを作成しましょう。
name_patternに対して.findall()メソッドを呼び出し、message内で一致するすべての単語を取得しましょう。respond()関数の中でfind_name()を呼び出し、「回答を送信」 をクリックして、ボットが各メッセージにどう応答するか確認しましょう。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Define find_name()
def find_name(message):
name = None
# Create a pattern for checking if the keywords occur
name_keyword = ____
# Create a pattern for finding capitalized words
name_pattern = ____
if name_keyword.search(message):
# Get the matching words in the string
name_words = ____
if len(name_words) > 0:
# Return the name if the keywords are present
name = ' '.join(name_words)
return name
# Define respond()
def respond(message):
# Find the name
name = ____
if name is None:
return "Hi there!"
else:
return "Hello, {0}!".format(name)
# Send messages
send_message("my name is David Copperfield")
send_message("call me Ishmael")
send_message("People call me Cassandra")