forked from explosion/spacy-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exc_02_15.py
34 lines (27 loc) · 1.07 KB
/
exc_02_15.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import spacy
from spacy.matcher import PhraseMatcher
from spacy.tokens import Span
import json
with open("exercises/en/countries.json") as f:
COUNTRIES = json.loads(f.read())
with open("exercises/en/country_text.txt") as f:
TEXT = f.read()
nlp = spacy.load("en_core_web_sm")
matcher = PhraseMatcher(nlp.vocab)
patterns = list(nlp.pipe(COUNTRIES))
matcher.add("COUNTRY", None, *patterns)
# docを作成し、固有表現リストをリセット
doc = nlp(TEXT)
doc.ents = []
# matchesをイテレート
for match_id, start, end in matcher(doc):
# 「GPE」のラベルを付けてスパンを作成
span = ____(____, ____, ____, label=____)
# doc.entsを上書きし、スパンを追加
doc.ents = list(doc.ents) + [____]
# スパンのルートヘッドトークンを取得
span_root_head = ____.____.____
# スパンのルートヘッドトークンとスパンの文字列をプリント
print(span_root_head.____, "-->", span.text)
# docの固有表現をプリント
print([(ent.text, ent.label_) for ent in doc.ents if ent.label_ == "GPE"])