从给定索引和文本源的令牌中重新创建多令牌字符串

问题描述 投票:0回答:1

我正在准备一个脚本,用于从标记化文本中为具有特定标签的标记重构多标记字符串。我的令牌与其原始文本中的开始和结束索引相关联。

这是一段示例文本:

t = "Breakfast at Tiffany's is a novella by Truman Capote."

包含原始文本索引和标签的令牌数据结构:

[(['Breakfast', 0, 9], 'BOOK'),
 (['at', 10, 12], 'BOOK'),
 (['Tiffany', 13, 20], 'BOOK'),
 (["'", 20, 21], 'BOOK'),
 (['s', 21, 22], 'BOOK'),
 (['is', 23, 25], 'O'),
 (['a', 26, 27], 'O'),
 (['novella', 28, 35], 'O'),
 (['by', 36, 38], 'O'),
 (['Truman', 39, 45], 'PER'),
 (['Capote', 46, 52], 'PER'),
 (['.', 52, 53], 'O')]

此数据结构是根据t如下生成的

import re

tokens = [[m.group(0), m.start(), m.end()] for m in re.finditer(r"\w+|[^\w\s]", t, re.UNICODE)]
tags = ['BOOK', 'BOOK', 'BOOK', 'BOOK', 'BOOK', 'O', 'O', 'O', 'O', 'PER', 'PER', 'O']
token_tuples = list(zip(tokens, tags))

[我希望脚本执行的操作是循环访问token_tuples,如果遇到非O令牌,它将脱离主迭代并重构标记的多令牌跨度,直到它到达最近的令牌用O

这是当前脚本:

for i in range(len(token_tuples)):

    if token_tuples[i][1] != 'O':

        tag = token_tuples[i][1]
        start_ix = token_tuples[i][0][1]

        slider = i+1

        while slider < len(token_tuples):

            if tag != token_tuples[slider][1]:

                end_ix = token_tuples[slider][0][2]

                print((t[start_ix:end_ix], tag))
                break

            else:
                slider+=1

此打印:

("Breakfast at Tiffany's is", 'BOOK')
("at Tiffany's is", 'BOOK')
("Tiffany's is", 'BOOK')
("'s is", 'BOOK')
('s is', 'BOOK')
('Truman Capote.', 'PER')
('Capote.', 'PER')

需要修改的内容,以便本示例的输出为:

> ("Breakfast at Tiffany's", "BOOK")
> ("Truman Capote", "PER")
python string iteration string-matching re
1个回答
0
投票

这里是一个解决方案。如果您能提出一些不太费劲的方法,那么我很乐意选择您的答案!

def extract_entities(t, token_tuples):

    entities = []
    tag = ''

    for i in range(len(token_tuples)):

        if token_tuples[i][1] != 'O':

            if token_tuples[i][1] != tag:
                tag = token_tuples[i][1]
                start_ix = token_tuples[i][0][1]

            else:
                tag = token_tuples[i][1]
                start_ix = token_tuples[i][0][1]

            slider = i+1

            while slider < len(token_tuples):

                if tag != token_tuples[slider][1]:

                    end_ix = token_tuples[slider-1][0][2]

                    entities.append((t[start_ix:end_ix], tag))
                    i = slider
                    break

                else:
                    i = slider
                    break

    return(entities)

© www.soinside.com 2019 - 2024. All rights reserved.