creating and visualizing spacy spans

Question:

I have a problem visualizing manually created spans in spacy:

given the simple code:

from spacy.tokens import Span
text = "Welcome to the Bank of China. "
nlp = spacy.blank("en")
doc = nlp(text)

doc.spans["xx"] = [Span(doc, 0, 1, "ORG")]
doc.spans["sc"] = [
    Span(doc, 3, 6, "ORG"), 
    Span(doc, 5, 6, "GPE"),
    Span(doc, 2, 4, "welcome")
]

the following visualizer works:

displacy.render(doc, style="span")

enter image description here

but if the spans do not contain the key "SC" it does not work

enter image description here

The error is key error "sc"

What is the problem there? why is the rendering not showing me all the spans?
The code giving the error is:

doc.spans["xx"] = [
    Span(doc, 3, 6, "ORG"), 
    Span(doc, 5, 6, "GPE"),
    Span(doc, 2, 4, "welcome")
]
displacy.render(doc, style="span", options ={"spans_key":"xx"})
Asked By: JFerro

||

Answers:

As explained in the displaCy documentation, by default the spans in the key "sc" are used. You can change it with the spans_key parameter.

render doesn’t take spans_key correctly, you have to include it in options.

From the docs, modified to use render instead of serve:

doc.spans["custom"] = [Span(doc, 3, 6, "BANK")]
options = {"spans_key": "custom"}
displacy.render(doc, style="span", options=options)
Answered By: polm23
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.