gpt4 book ai didi

python - 在元组列表中查找特定类型的一个或多个字符串

转载 作者:行者123 更新时间:2023-12-01 03:52:07 24 4
gpt4 key购买 nike

假设我有以下元组:

tagged = [('They', 'PRP'),
('refuse', 'VBP'),
('to', 'TO'),
('permit', 'VB'),
('us', 'PRP'),
('to', 'TO'),
('obtain', 'VB'),
('the', 'DT'),
('refuse', 'NN'),
('permit', 'NN')]

我想采用一个或多个名词(按顺序排列)的所有组合。因此,输出将是:

['refuse','permit','refuse permit']

我能够像这样得到前两个:

filtered = [x[0] for x in tagged if x[1]=='NN']

但我目前无法找到获取列表中 'NN' 序列的方法。

编辑:

这个列表是一个更好的例子:

 [('If', 'IN'),
('the', 'DT'),
('company', 'NN'),
('name', 'NN'),
('or', 'CC'),
('job', 'NN'),
('title', 'NN'),
('includes', 'VBZ'),
('multiple', 'JJ'),
('words', 'NNS'),
(',', ','),
('use', 'NN'),
('double', 'JJ'),
('quotation', 'NN'),
('marks', 'NNS'),
('.', '.')]

应该返回:

['company', 'name', 'company name', 'job', 'title', 'job title', 'use', 'quotation']

最佳答案

这是一个非常简单的groupby操作,需要进行一些处理。如果我们按标签分组并且只查看名词组,那么我们就差不多完成了。然后唯一要做的就是加入具有超过 1 个项目的组,并将这些内容按正确的顺序放入输出中:

from itertools import groupby

def group_nouns(iterable):
for key, group in groupby(iterable, key=lambda t: t[1]):
if key == 'NN': # only worry about groups of nouns.
seq = [t[0] for t in group] # drop tags.
if len(seq) == 1:
yield seq[0]
else:
for noun in seq:
yield noun
yield ' '.join(seq)

关于python - 在元组列表中查找特定类型的一个或多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38057632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com