从lis中删除类似项

2024-03-28 13:25:47 发布

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

我有一个单词列表(近7项),我想删除与其他单词几乎相同的单词(即如果我的单词是“代理账户银行协议”,我想删除类似“代理账户银行协议”的单词)。你知道吗

为了估计一个单词是否接近另一个单词,我使用了Python中水母包的Jaro距离。你知道吗

我现在的代码是:

corpus3 = ['Agency Account Bank Agreement', 'Agent', 'Agency Account Bank Agreement Pursuant',
       'Agency Account Bank Agreement Notwithstanding', 'Agents', 'Agent', 'Reinvestment Period']
threshold = 0,85
for a, b in itertools.combinations(corpus3, 2):
    if len(a.split()) >= 2 or len(b.split()) >= 2:               
        jf = jellyfish.jaro_distance(a, b)
        if jf > threshold:
            if a in new_corpus and b in new_corpus:                
                continue
            else:
                if len(a.strip()) < len(b.strip()):
                    kw = a
                    if not new_corpus:
                        new_corpus.append(a)
                    else:    
                        for item in new_corpus:
                            jf = jellyfish.jaro_distance(kw, item)
                            if jf < threshold:
                                new_corpus.append(kw)

这就是我最后想要的:

new_corpus = ['Agency Account Bank Agreement', 'Agent', 'Reinvestment Period']

Tags: in代理newthresholdlenifagreementaccount
1条回答
网友
1楼 · 发布于 2024-03-28 13:25:47

假设您有以下列表:

numchars = ['one', 'ones', 'two', 'twos', 'three', 'threes']

假设您认为oneones太相似,您只想保留其中一个,这样您修改后的列表将类似于:

numchars = ['ones', 'twos', 'threes']

你可以这样做,以消除那些你认为太相似的:

for x in numchars:
    if any(lower_threshold < jellyfish.jaro_distance(x, _x) and x != _x for _x in numchars):
        numchars.remove(x)

根据您设置的阈值以及列表的顺序,这可能会产生如下结果:

numchars = ['ones', 'twos', 'threes']

此例程的主要逻辑如下:

if any(lower_threshold < jellyfish.jaro_distance(x, _x) and x != _x for _x in numchars):

这表示如果列表numchars中的任何成员与该列表中除自身以外的所有成员相比,其相似度等级大于您定义的lower_threshold,则应将该成员从列表中删除,例如:numchars.remove(x)。另外,and x != _x条件避免了注册一个与自身太相似的成员。你知道吗

但可以说,三明治的肉是这样的:

numchars.remove(x)

这个语句确保一旦你删除了one因为它与ones太相似,那么在下一次迭代中one就不再是列表的成员了,也不会与ones进行比较,从而删除ones。这种方法最终会导致一个空列表。你知道吗

一旦你开始只想保持多元化,或其他形式的类似匹配组,你打开了一个完整的另一个可以蠕虫。你知道吗

相关问题 更多 >