Python spacy ライブラリ完全ガイド

Python の spacy は、文章解析に特化した高速で強力な自然言語処理 (NLP) ライブラリです。
1. spacy ライブラリの概要
- トークン化(Tokenization)
- 哲学解析(Part-of-speech tagging)
- 名詞識別(Named Entity Recognition)
- 依存構文解析(Dependency Parsing)
インストール方法
pip install spacy
python -m spacy download ja_core_news_sm
2. 主な機能と使用例
(1) 基本的な文章解析
import spacy nlp = spacy.load("ja_core_news_sm") doc = nlp("Appleは新しいiPhoneを発表した") for token in doc: print(token.text, token.pos_, token.dep_)
(2) 名詞識別 (NER)
for ent in doc.ents: print(ent.text, ent.label_)
(3) 文の一覧を分解
for sent in doc.sents: print(sent.text)
(4) 用語の基本情報
for token in doc: print(token.text, "POS:", token.pos_, "Lemma:", token.lemma_)
(5) 依存構文解析
for token in doc: print(token.text, "->", token.head.text, f"({token.dep_})")
(6) 合成語解析
for chunk in doc.noun_chunks: print(chunk.text, "--", chunk.root.text)
(7) 不要な語の除去 (Stopwords)
print([token.text for token in doc if not token.is_stop])
(8) 類似語検出 (単語のベクトル)
# Word2Vec や Transformer モデルを使用する場合、spaCyはラッパー型モデルを依存として載せることも可能 similar = nlp("現金").similarity(nlp("金銭")) print("類似度:", similar)
(9) 単語の検出
for token in doc: if token.pos_ == "NOUN": print(token.text)
(10) 未来用: 図表化 / displaCy
from spacy import displacy displacy.serve(doc, style="ent")
3. spacy の主なモジュール
| 機能 | 説明 |
|---|---|
Token |
文章を分解した最小単位の語 |
Doc |
文章の解析結果 |
Span |
文章の一部分(複数のToken) |
Matcher |
ルールベース検索用API |
まとめ
spacy はシンプルなコードで文章分析が可能な最先線のNLPライブラリです。
日本語モデルも完備され、現場でも使える高性能な自然言語解析を実現できます 🚀