Có vẻ dài nhưng nó công trình:
ner_output = [(u'Remaking', u'O'), (u'The', u'O'), (u'Republican', u'ORGANIZATION'), (u'Party', u'ORGANIZATION')]
chunked, pos = [], ""
for i, word_pos in enumerate(ner_output):
word, pos = word_pos
if pos in ['PERSON', 'ORGANIZATION', 'LOCATION'] and pos == prev_tag:
chunked[-1]+=word_pos
else:
chunked.append(word_pos)
prev_tag = pos
clean_chunked = [tuple([" ".join(wordpos[::2]), wordpos[-1]]) if len(wordpos)!=2 else wordpos for wordpos in chunked]
print clean_chunked
[ra]:
[(u'Remaking', u'O'), (u'The', u'O'), (u'Republican Party', u'ORGANIZATION')]
Để biết thêm chi tiết:
Đầu tiên cho vòng lặp "với bộ nhớ "đạt được điều gì đó như thế này:
[(u'Remaking', u'O'), (u'The', u'O'), (u'Republican', u'ORGANIZATION', u'Party', u'ORGANIZATION')]
Bạn sẽ nhận thấy rằng tất cả các tên Enitties sẽ có nhiều hơn 2 mục trong một bộ và những gì bạn muốn là các từ như các phần tử trong danh sách, tức là 'Republican Party'
trong (u'Republican', u'ORGANIZATION', u'Party', u'ORGANIZATION')
, vì vậy bạn sẽ làm một cái gì đó như thế này để có được thậm chí yếu tố:
>>> x = [0,1,2,3,4,5,6]
>>> x[::2]
[0, 2, 4, 6]
>>> x[1::2]
[1, 3, 5]
Sau đó, bạn cũng nhận ra rằng yếu tố cuối cùng trong tuple NE là thẻ mà bạn muốn, do đó bạn sẽ làm `
>>> x = (u'Republican', u'ORGANIZATION', u'Party', u'ORGANIZATION')
>>> x[::2]
(u'Republican', u'Party')
>>> x[-1]
u'ORGANIZATION'
đó là một chút ad-hoc và vebose nhưng Tôi hy vọng nó sẽ giúp. Và ở đây nó là một chức năng, Phúc cho Giáng sinh:
ner_output = [(u'Remaking', u'O'), (u'The', u'O'), (u'Republican', u'ORGANIZATION'), (u'Party', u'ORGANIZATION')]
def rechunk(ner_output):
chunked, pos = [], ""
for i, word_pos in enumerate(ner_output):
word, pos = word_pos
if pos in ['PERSON', 'ORGANIZATION', 'LOCATION'] and pos == prev_tag:
chunked[-1]+=word_pos
else:
chunked.append(word_pos)
prev_tag = pos
clean_chunked = [tuple([" ".join(wordpos[::2]), wordpos[-1]])
if len(wordpos)!=2 else wordpos for wordpos in chunked]
return clean_chunked
print rechunk(ner_output)
Chỉ cần bắt đầu học java ... – Cosmozhang