給的輸入句子,具有BIO chunk tags:如何從BIO分塊句子中提取塊? - 蟒
[( '什麼', 'B-NP'),( '是', 'B-VP'),( '的',' ('','B-NP'),('空速', 'I-NP'),('','B-PP'),('an','B-NP'),('unladen','I -NP '), (' 吞」, 'I-NP'),( '?', 'O')]
我需要提取相關的短語進行,例如如果我想提取'NP'
,我需要提取包含B-NP
和I-NP
的元組片段。
[OUT]:
[('What', '0'), ('the airspeed', '2-3'), ('an unladen swallow', '5-6-7')]
(注:在提取物中的元組中的數字表示的標記索引。)
我曾嘗試使用以下代碼中提取它:
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')))
但是當我有相鄰類型的相鄰塊時:
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')))
它輸出這樣的:
[('The Mitsubishi Electric Company Managing Director', '0-1-2-3-4-5'), ('ramen', '7')]
代替所需的:
[('The Mitsubishi Electric Company', '0-1-2-3'), ('Managing Director', '4-5'), ('ramen', '7')]
這怎麼可能從上面的代碼解決?
除了上面的代碼是如何完成的,是否有更好的解決方案來提取特定的chunk_type
所需的塊?