在轉錄文字上做命名實體辨識

Python 的口語語言處理

Daniel Bourke

Machine Learning Engineer/YouTube Creator

安裝 spaCy

# Install spaCy
$ pip install spacy
# Download spaCy language model
$ python -m spacy download en_core_web_sm
Python 的口語語言處理

使用 spaCy

import spacy

# Load spaCy language model nlp = spacy.load("en_core_web_sm")
# Create a spaCy doc
doc = nlp("I'd like to talk about a smartphone I ordered on July 31st from your 
Sydney store, my order number is 40939440. I spoke to Georgia about it last week.")
Python 的口語語言處理

spaCy 詞元(tokens)

# Show different tokens and positions
for token in doc:
  print(token.text, token.idx)
I 0
'd 1
like 4
to 9
talk 12
about 17
a 23
smartphone 25...
Python 的口語語言處理

spaCy 句子

# Show sentences in doc
for sentences in doc.sents:
  print(sentence)
I'd like to talk about a smartphone I ordered on July 31st from your Sydney store, 
my order number is 4093829.
I spoke to one of your customer service team, Georgia, yesterday.
Python 的口語語言處理

spaCy 命名實體

spaCy 內建的一些命名實體:

  • PERSON 人名(含虛構角色)。
  • ORG 組織(公司、機構等)。
  • GPE 地緣政治實體(國家、城市、州)。
  • PRODUCT 產品(物件、車輛、食物等;不含服務)。
  • DATE 日期或期間(絕對或相對)。
  • TIME 小於 1 天的時間。
  • MONEY 金額(含幣別)。
  • CARDINAL 非其他類別的基數詞。
Python 的口語語言處理

spaCy 命名實體

# Find named entities in doc
for entity in doc.ents:
  print(entity.text, entity.label_)
July 31st DATE
Sydney GPE
4093829 CARDINAL
one CARDINAL
Georgia GPE
yesterday DATE
Python 的口語語言處理

自訂命名實體

# Import EntityRuler class
from spacy.pipeline import EntityRuler
# Check spaCy pipeline
print(nlp.pipeline)
[('tagger', <spacy.pipeline.pipes.Tagger at 0x1c3aa8a470>),
 ('parser', <spacy.pipeline.pipes.DependencyParser at 0x1c3bb60588>),
 ('ner', <spacy.pipeline.pipes.EntityRecognizer at 0x1c3bb605e8>)]
Python 的口語語言處理

調整 pipeline

# Create EntityRuler instance
ruler = EntityRuler(nlp)
# Add token pattern to ruler
ruler.add_patterns([{"label":"PRODUCT", "pattern": "smartphone"}])
# Add new rule to pipeline before ner
nlp.add_pipe(ruler, before="ner")
# Check updated pipeline
nlp.pipeline
Python 的口語語言處理

調整 pipeline

[('tagger', <spacy.pipeline.pipes.Tagger at 0x1c1f9c9b38>),
 ('parser', <spacy.pipeline.pipes.DependencyParser at 0x1c3c9cba08>),
 ('entity_ruler', <spacy.pipeline.entityruler.EntityRuler at 0x1c1d834b70>),
 ('ner', <spacy.pipeline.pipes.EntityRecognizer at 0x1c3c9cba68>)]
Python 的口語語言處理

測試新的 pipeline

# Test new entity rule
for entity in doc.ents:
    print(entity.text, entity.label_)
smartphone PRODUCT
July 31st DATE
Sydney GPE
4093829 CARDINAL
one CARDINAL
Georgia GPE
yesterday DATE
Python 的口語語言處理

出發,來練習 spaCy!

Python 的口語語言處理

Preparing Video For Download...