Turn a sequence of BIO tags back into the entities it describes.
What to build
A program that prints the entities encoded by BIO tags.
Requirements
- Line 1 holds the words and line 2 one tag per word:
O,B-TYPEorI-TYPE. - B-TYPE starts a new entity. I-TYPE continues the current entity if it has the same type, and otherwise starts a new one. O ends any current entity.
- Print each entity as
TYPE: words, in order, orno entitiesif there are none.
Input
Two lines: the words, then the tags.
Output
One line per entity, or one line.
Constraints
At most 1,000 words.
Example
Input:
Ada Lovelace visited London in 1843
B-PER I-PER O B-LOC O B-DATE
Output:
PER: Ada Lovelace
LOC: London
DATE: 1843
Why it works
BIO tags mark where each entity begins and continues, so a single left-to-right pass rebuilds every span, and the lenient rule for a stray I- tag never loses a word that a tagger labelled as part of an entity.
Examples
Ada Lovelace visited London in 1843 B-PER I-PER O B-LOC O B-DATE
PER: Ada Lovelace LOC: London DATE: 1843
New York New Jersey B-LOC I-LOC B-LOC I-LOC
LOC: New York LOC: New Jersey
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep the current entity as `[type, words]`; `kind, label = tag.split("-", 1)` separates B or I from the type.
Hint 2
An I- tag continues the current entity only if the current entity has the same type; otherwise it starts a new one.
Solution
Show one correct solution (try it yourself first)
words = input().split()
tags = input().split()
spans, current = [], None
for w, t in zip(words, tags):
if t == "O":
current = None
continue
kind, label = t.split("-", 1)
if kind == "I" and current and current[0] == label:
current[1].append(w)
else:
current = [label, [w]]
spans.append(current)
for label, ws in spans:
print(f"{label}: {' '.join(ws)}")
if not spans:
print("no entities")