Dare una frase di input, che ha BIO chunk tags:Come estrarre i pezzi dalle frasi BIO Chunked? - pitone
[('Che', 'B-NP'), ('è', 'B-VP'), ('la', ' B-NP '), (' velocità ', ' I-NP '), (' of ',' B-PP '), (' an ',' B-NP '), (' vuoto ',' I -NP '), (' ingoiare', 'i-NP'), ('?', 'O')]
avrei bisogno di estrarre le frasi rilevanti, ad es se voglio estrarre 'NP'
, avrei bisogno di estrarre i frammenti di tuple che contengono B-NP
e I-NP
.
[out]:
[('What', '0'), ('the airspeed', '2-3'), ('an unladen swallow', '5-6-7')]
(Nota: i numeri nelle tuple estratto rappresentano l'indice di token.)
ho provato l'estrazione utilizzando il seguente codice:
def extract_chunks(tagged_sent, chunk_type):
current_chunk = []
current_chunk_position = []
for idx, word_pos in enumerate(tagged_sent):
word, pos = word_pos
if '-'+chunk_type in pos: # Append the word to the current_chunk.
current_chunk.append((word))
current_chunk_position.append((idx))
else:
if current_chunk: # Flush the full chunk when out of an NP.
_chunk_str = ' '.join(current_chunk)
_chunk_pos_str = '-'.join(map(str, current_chunk_position))
yield _chunk_str, _chunk_pos_str
current_chunk = []
current_chunk_position = []
if current_chunk: # Flush the last chunk.
yield ' '.join(current_chunk), '-'.join(current_chunk_position)
tagged_sent = [('What', 'B-NP'), ('is', 'B-VP'), ('the', 'B-NP'), ('airspeed', 'I-NP'), ('of', 'B-PP'), ('an', 'B-NP'), ('unladen', 'I-NP'), ('swallow', 'I-NP'), ('?', 'O')]
print (list(extract_chunks(tagged_sent, chunk_type='NP')))
Ma quando ho un blocco adiacente dello stesso tipo:
tagged_sent = [('The', 'B-NP'), ('Mitsubishi', 'I-NP'), ('Electric', 'I-NP'), ('Company', 'I-NP'), ('Managing', 'B-NP'), ('Director', 'I-NP'), ('ate', 'B-VP'), ('ramen', 'B-NP')]
print (list(extract_chunks(tagged_sent, chunk_type='NP')))
Produce questo:
[('The Mitsubishi Electric Company Managing Director', '0-1-2-3-4-5'), ('ramen', '7')]
Invece della desiderata:
[('The Mitsubishi Electric Company', '0-1-2-3'), ('Managing Director', '4-5'), ('ramen', '7')]
come può essere risolto dal codice di cui sopra?
Diverso da come è fatto dal codice sopra, c'è una soluzione migliore per estrarre i blocchi desiderati di uno specifico chunk_type
?