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.03 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", encoding="utf8") as f:
COUNTRIES = json.loads(f.read())
with open("exercises/en/country_text.txt", encoding="utf8") as f:
TEXT = f.read()
nlp = spacy.load("en_core_web_sm")
matcher = PhraseMatcher(nlp.vocab)
patterns = list(nlp.pipe(COUNTRIES))
matcher.add("COUNTRY", patterns)
# Create a doc and reset existing entities
doc = nlp(TEXT)
doc.ents = []
# Iterate over the matches
for match_id, start, end in matcher(doc):
# Create a Span with the label for "GPE"
span = ____(____, ____, ____, label=____)
# Overwrite the doc.ents and add the span
doc.ents = list(doc.ents) + [____]
# Get the span's root head token
span_root_head = ____.____.____
# Print the text of the span root's head token and the span text
print(span_root_head.____, "-->", span.text)
# Print the entities in the document
print([(ent.text, ent.label_) for ent in doc.ents if ent.label_ == "GPE"])