MaybeNextTime
MaybeNextTime

Reputation: 611

Get Stanford NER result through NLTK with IOB format

i'm using nltk as interface for Stanford NER Tagger. I have question that are there any options to get NER result as IOB format using NLTK? I've read this question but it's for java user

NLTK version: 3.4

Java version: jdk1.8.0_211/bin

Stanford NER model: english.conll.4class.distsim.crf.ser.gz

Input: My name is Donald Trumph

Expected output: My/O name/O is/O Donald/B-PERSON Trumph/I-PERSON

Upvotes: 0

Views: 388

Answers (1)

alvas
alvas

Reputation: 122012

TL;DR

First see Stanford Parser and NLTK

Write a simple loop and iterate through the NER outputs:

def stanford_to_bio(tagged_sent):
    prev_tag = "O"
    bio_tagged_output = []
    current_ner = []
    for word, tag in tagged_sent:
        if tag == 'O':
            bio_tagged_output += current_ner
            bio_tagged_output.append((word, tag))
            current_ner = []
            prev_tag = 'O'
        else:
            if prev_tag == 'O':
                current_ner.append((word, 'B-'+tag))
                prev_tag = 'B'
            else:
                current_ner.append((word, 'I-'+tag))
                prev_tag = 'I'
    if current_ner:
        bio_tagged_output += current_ner
    return bio_tagged_output

tagged_sent = [('Rami', 'PERSON'), ('Eid', 'PERSON'), ('is', 'O'), ('studying', 'O'), ('at', 'O'), ('Stony', 'ORGANIZATION'), ('Brook', 'ORGANIZATION'), ('University', 'ORGANIZATION'), ('in', 'O'), ('NY', 'STATE_OR_PROVINCE')]
stanford_to_bio(tagged_sent)

[out]:

[('Rami', 'B-PERSON'),
 ('Eid', 'I-PERSON'),
 ('is', 'O'),
 ('studying', 'O'),
 ('at', 'O'),
 ('Stony', 'B-ORGANIZATION'),
 ('Brook', 'I-ORGANIZATION'),
 ('University', 'I-ORGANIZATION'),
 ('in', 'O'),
 ('NY', 'B-STATE_OR_PROVINCE')]

Upvotes: 1

Related Questions