假设我有以下元组:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句