在特定元素的实例之后从列表中提取相同的元素块

2024-06-24 12:38:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从列表中提取连续的'NN'元素(包括'NNP'),并附加到一个新的列表中,如果在'NN'之前遇到'IN'或'to'。我该怎么做?你知道吗

我尝试了以下代码。但无法捕捉到其他类似的例子。你知道吗

    new = ['JJ',
 'NN',
 'IN',
 'NNP',
 'NN',
 'MD',
 'VB',
 'VBN',
 'IN',
 'NN',
 'TO',
 'VB',
 'NN',
 'CC',
 'NN',
 'TO',
 'NNP',
 'NN',
 'NN',
 '.']

lst = []
for i,j in enumerate(new):
    lst1 = []
    if j == 'IN':
        for i in new[i+1:]:
            if 'NN' in i:
                lst1.append(i)
                lst.append(lst1)
                break

lst = [['NNP'], ['NN']]

但我想改进代码,得到以下输出:

[['NNP', 'NN'], ['NN'], ['NNP', 'NN', 'NN']

每个输出块的前面都有“IN”或“TO”。你知道吗

实际上,上面的列表(新的)是这个列表的基本词类:

[['Additional',
  'condition',
  'of',
  'DeNOx',
  'activation',
  'shall',
  'be',
  'introduced',
  'in',
  'order',
  'to',
  'provide',
  'flexibility',
  'and',
  'robustness',
  'to',
  'NSC',
  'regeneration',
  'management',
  '.'],
 ['JJ',
  'NN',
  'IN',
  'NNP',
  'NN',
  'MD',
  'VB',
  'VBN',
  'IN',
  'NN',
  'TO',
  'VB',
  'NN',
  'CC',
  'NN',
  'TO',
  'NNP',
  'NN',
  'NN',
  '.']].

如何将结果映射回此列表以便

[['DeNOx', 'activation'], ['order'], ['NSC', 'regeneration', 'management']]

Tags: to代码in列表newnnmdvb
3条回答

有另一个很好的答案张贴,而我正在键入这是一个简单的实现没有导入。你知道吗

full_list = []

for x in range(0, len(new)):
    if 'NN' in new[x] and ('IN' in new[x-1] or 'TO' in new[x-1]):
        temp_list = [new[x]]
        temp_index = x+1
        while 'NN' in new[temp_index]:
            temp_list.append(new[temp_index])
            temp_index += 1
        full_list.append(temp_list)

你的车不太远。使之更容易的一种方法是获取'IN''TO'的所有索引:

starts = {'IN', 'TO'}
in_twos = [i for i, e in enumerate(new) if e in starts]

它给出:

[2, 8, 10, 15]

然后您只需要遍历这些索引,特别是new[i+1:],并获取'NN''NNP'元素。当您到达一个不是这些元素之一的元素时,break将退出循环。你知道吗

举个例子:

result = []
take = {'NN', 'NNP'}

for i in in_twos:
    temp = []
    for x in new[i+1:]:
        if x not in take:
            break

        temp.append(x)

    # If this is empty, don't add it
    if temp:
        result.append(temp)

print(result)

最终输出:

[['NNP', 'NN'], ['NN'], ['NNP', 'NN', 'NN']]

另一个较短的方法,如@schwobasegll所建议的,是使用^{}来简化'NN'元素的提取。这个函数基本上一直提取元素,直到第一个参数谓词返回false。你知道吗

下面是它的样子:

from itertools import takewhile

# new, take and in_twos same as before

result = [l for l in [list(takewhile(lambda x: x in take, new[i+1:])) for i in in_twos] if l]

print(result)
# [['NNP', 'NN'], ['NN'], ['NNP', 'NN', 'NN']]

更新:

如果要将单词和演讲映射到一起,可以执行以下操作:

new = [['JJ', 'NN', 'IN','NNP','NN','MD','VB','VBN','IN','NN','TO','VB','NN','CC','NN','TO','NNP','NN','NN','.'],
   ['Additional','condition','of','DeNOx','activation','shall','be','introduced','in', 'order','to','provide','flexibility','and','robustness', 'to','NSC','regeneration','management','.']]

starts = {'IN', 'TO'}
in_twos = [i for i, e in enumerate(new[0]) if e in starts]

speech = []
words = []
take = {'NN', 'NNP'}

for i in in_twos:
    temp = []
    for x, y in zip(new[0][i+1:], new[1][i+1:]):
        if x not in take:
            break

        temp.append((x, y))

    # If this is empty, don't add it
    if temp:
        speech.append([x for x, _ in temp])
        words.append([y for _, y in temp])

print(speech)
print(words)

输出:

[['NNP', 'NN'], ['NN'], ['NNP', 'NN', 'NN']]
[['DeNOx', 'activation'], ['order'], ['NSC', 'regeneration', 'management']]

您可以使用两个方便的^{}来实现:^{}^{}

from itertools import groupby, takewhile

nn = lambda x: x.startswith('NN')
to_in = lambda x: x in ('IN', 'TO')

list(filter(None, [list(takewhile(nn, g)) for k, g in groupby(new, key=to_in)][1:]))
# [['NNP', 'NN'], ['NN'], ['NNP', 'NN', 'NN']]

它根据TOIN的项目将初始列表分块。从除第一个以外的每个块(为了避免任何初始的NNs),这将在元素以NN开头时获取元素。最后,它filters输出非真实(空)列表。你知道吗

相关问题 更多 >