spaCy の拡張構文でのマッチング
ルールベースの情報抽出は、あらゆるNLPパイプラインにとって重要です。Matcher クラスでは、中かっこ内にいくつかの演算子を使えるため、より表現力のあるパターンを定義できます。これらの演算子は、拡張比較のためのもので、Python の in / not in や比較演算子に似ています。この演習では、spaCy のマッチング機能である Matcher を使って、サンプルテキストから指定の用語に一致する箇所を見つける練習をします。
Matcher クラスはすでに spacy.matcher ライブラリからインポートされています。この演習では、例文の Doc コンテナとして doc を使用します。事前に読み込まれた spaCy モデルは nlp で参照できます。
この演習はコースの一部です
spaCyで学ぶNatural Language Processing
演習の手順
Matcherとnlpを使って matcher オブジェクトを定義します。IN演算子を使って、tiny squaresとtiny mouthfulにマッチするパターンを定義します。- このパターンを使って
docの一致箇所を見つけます。 - 一致した開始・終了トークンのインデックスと、そのテキストスパンを出力します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
nlp = spacy.load("en_core_web_sm")
doc = nlp(example_text)
# Define a matcher object
matcher = Matcher(nlp.____)
# Define a pattern to match tiny squares and tiny mouthful
pattern = [{"lower": ____}, {"lower": {____: ["squares", "mouthful"]}}]
# Add the pattern to matcher object and find matches
matcher.____("CustomMatcher", [____])
matches = ____(____)
# Print out start and end token indices and the matched text span per match
for match_id, start, end in matches:
print("Start token: ", ____, " | End token: ", ____, "| Matched text: ", doc[____:____].text)