spaCy の PhraseMatcher
非構造化テキストを処理する際、与えられたテキスト内で走査・照合したい長いリストや辞書を扱うことがよくあります。Matcher のパターンは手作業で作成し、各トークンを個別に記述する必要があります。フレーズのリストが長い場合は、Matcher は最適ではありません。こうした場面では、PhraseMatcher クラスを使うと大きな辞書の照合が行えます。この演習では、PhraseMatcher クラスを用いて、複数の用語に対して同じ形状に一致するパターンを取得する練習をします。
en_core_web_sm モデルはすでに読み込まれており、nlp として利用できます。PhraseMatcher クラスはインポート済みです。text 文字列と terms のリストも用意されています。
この演習はコースの一部です
spaCyで学ぶNatural Language Processing
演習の手順
- 指定された
termsの形状にマッチさせるため、attrを指定してPhraseMatcherクラスを初期化します。 PhraseMatcherオブジェクトに追加するためのpatternsを作成します。- 与えられたパターンに対するマッチを見つけ、
textの開始・終了トークンのインデックスと一致した部分を出力します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
text = "There are only a few acceptable IP addresse: (1) 127.100.0.1, (2) 123.4.1.0."
terms = ["110.0.0.0", "101.243.0.0"]
# Initialize a PhraseMatcher class to match to shapes of given terms
matcher = ____(nlp.____, attr = ____)
# Create patterns to add to the PhraseMatcher object
patterns = [nlp.make_doc(____) for term in terms]
matcher.____("IPAddresses", patterns)
# Find matches to the given patterns and print start and end characters and matches texts
doc = ____
matches = ____
for match_id, start, end in matches:
print("Start token: ", ____, " | End token: ", ____, "| Matched text: ", doc[____:____].text)