使用 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 會在 nlp 管線的 pos_ 特徵中保存 POS 標籤spacy.explain() 可解釋指定的 POS 標籤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 | 小於 1 天的時間 |
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 容器中讀取每個 token 的實體類型
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 的自然語言處理