使用 spaCy 的自然语言处理
Azadeh Mobasher
Principal Data Scientist
import spacynlp = spacy.load("en_core_web_sm")doc = nlp("Here's my spaCy pipeline.")
spaCyspacy.load() 返回 nlp(Language 类)Language 对象是文本处理管线nlp(),得到 Doc 容器
spaCy 使用其 Language 类执行一系列处理步骤:
spaCy 中有多种数据结构表示文本数据:
| 名称 | 说明 |
|---|---|
Doc |
访问文本语言学标注的容器 |
Span |
Doc 对象的片段 |
Token |
单个 token,如词、标点、空白等 |
spaCy 的语言处理管线取决于所加载模型及其能力。
| 组件 | 名称 | 说明 |
|---|---|---|
| Tokenizer | Tokenizer | 将文本切分为 token 并创建 Doc 对象 |
| Tagger | Tagger | 分配词性标签 |
| Lemmatizer | Lemmatizer | 将词还原为词元 |
| EntityRecognizer | NER | 识别并标注命名实体 |
每个组件都有处理文本的独特功能
import spacy nlp = spacy.load("en_core_web_sm") doc = nlp("Tokenization splits a sentence into its tokens.")print([token.text for token in doc])
['Tokenization', 'splits', 'a', 'sentence', 'into', 'its', 'tokens', '.']
DependencyParser 组件的一部分import spacy nlp = spacy.load("en_core_web_sm") text = "We are learning NLP. This course introduces spaCy." doc = nlp(text)for sent in doc.sents: print(sent.text)
We are learning NLP.
This course introduces spaCy.
import spacy nlp = spacy.load("en_core_web_sm") doc = nlp("We are seeing her after one year.")print([(token.text, token.lemma_) for token in doc])
[('We', 'we'), ('are', 'be'), ('seeing', 'see'), ('her', 'she'),
('after', 'after'), ('one', 'one'), ('year', 'year'), ('.', '.')]
使用 spaCy 的自然语言处理