使用 spaCy 的自然语言处理
Azadeh Mobasher
Principal Data Scientist
| POS | 描述 | 例子 |
|---|---|---|
| VERB | 动词 | run, eat, ate, take |
| NOUN | 名词 | man, airplane, tree, flower |
| ADJ | 形容词 | big, old, incompatible, conflicting |
| ADV | 副词 | very, down, there, tomorrow |
| CONJ | 连词 | and, or, but |
spaCy 在管道的 pos_ 特征中提供词性spacy.explain() 可解释给定词性标签verb_sent = "I watch TV."print([(token.text, token.pos_, spacy.explain(token.pos_)) for token in nlp(verb_sent)])
[('I', 'PRON', 'pronoun'),
('watch', 'VERB', 'verb'),
('TV', 'NOUN', 'noun'),
('.', 'PUNCT', 'punctuation')]
noun_sent = "I left without my watch."print([(token.text, token.pos_, spacy.explain(token.pos_)) for token in nlp(noun_sent)])
[('I', 'PRON', 'pronoun'),
('left', 'VERB', 'verb'),
('without', 'ADP', 'adposition'),
('my', 'PRON', 'pronoun'),
('watch', 'NOUN', 'noun'),
('.', 'PUNCT', 'punctuation')]
| 实体类型 | 描述 |
|---|---|
| PERSON | 指定的人或家族 |
| ORG | 公司、机构等 |
| GPE | 地缘政治实体,如国家、城市等 |
| LOC | 非 GPE 的地点,如山脉等 |
| DATE | 绝对或相对的日期/时期 |
| TIME | 小于一天的时间 |
spaCy 通过 NER 管道组件抽取命名实体doc.ents 属性获取spaCy 还会为每个实体标注类别标签(.label_)
import spacy nlp = spacy.load("en_core_web_sm") text = "Albert Einstein was genius." doc = nlp(text)print([(ent.text, ent.start_char, ent.end_char, ent.label_) for ent in doc.ents])
>>> [('Albert Einstein', 0, 15, 'PERSON')]
Doc 中逐词访问实体类型
import spacy nlp = spacy.load("en_core_web_sm") text = "Albert Einstein was genius." doc = nlp(text)print([(token.text, token.ent_type_) for token in doc])
>>> [('Albert', 'PERSON'), ('Einstein', 'PERSON'),
('was', ''), ('genius', ''), ('.', '')]
spaCy 提供现代可视化工具:displaCydisplaCy 的实体可视化会高亮实体及其标签import spacy from spacy import displacy text = "Albert Einstein was genius." nlp = spacy.load("en_core_web_sm") doc = nlp(text)displacy.serve(doc, style="ent")
使用 spaCy 的自然语言处理