简体   繁体   中英

Visualizing customized NER tags with SpaCy Displacy

I am new to spaCy and Python and I want to visualize a NER using this library. This is the sample example that I found:

import spacy
from spacy import displacy

NER = spacy.load("en_core_web_sm")

raw_text="The Indian Space Research Organisation or is the national space agency of India, headquartered in Bengaluru. It operates under Department of Space which is directly overseen by the Prime Minister of India while Chairman of ISRO acts as executive of DOS as well."

text1= NER(raw_text)

displacy.render(text1,style="ent",jupyter=True)

The Example of Visualization

However, I already have a list of customized tags and their positions:

 [812, 834, "POS"], [838, 853, "ORG"], [870, 888, "POS"], [892, 920, "ORG"], [925, 929, "ENGLEVEL"], [987, 1002, "SKILL"],...

I want my text to be visualized with my own customized tags and entities, instead of the default NER options of spaCy. How can I achieve this?

You will need to add char spans signifying entities and attach them to your doc object. Something like this:

import spacy
from spacy import displacy

nlp = spacy.blank('en')
raw_text = "The Indian Space Research Organisation or is the national space agency of India, headquartered in Bengaluru. It operates under Department of Space which is directly overseen by the Prime Minister of India while Chairman of ISRO acts as executive of DOS as well."
doc = nlp.make_doc(raw_text)
spans = [[812, 834, "POS"], [838, 853, "ORG"], [870, 888, "POS"], [892, 920, "ORG"], [925, 929, "ENGLEVEL"],
         [987, 1002, "SKILL"]]
ents = []
for span_start, span_end, label in spans:
    ent = doc.char_span(span_start, span_end, label=label)
    if ent is None:
        continue

    ents.append(ent)

doc.ents = ents
displacy.render(doc, style="ent", jupyter=True)

Change your raw_text and spans accordingly. If you give a span that starts or ends beyond the length of your text doc.char_span() returns None so you need to handle that appropriately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM