如何将列表中的一个句子与Python中出现在它后面的所有句子进行比较?

2024-10-05 14:22:15 发布

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

我有一张有1200句话的单子。我想计算列表中一个句子的Jaccard系数,后面还有其他所有的句子。 像sent1将与sent2,3,。。。然后用sent2和sent3,4,。。。 我已经有了一个函数,它接受2个集合并返回Jaccard系数。我只想知道如何为上述场景编写python循环。你知道吗

list_question=[] #This List is later filled with sentences from a file

def jaccard(a,b): # computes Jaccard
    c=a.intersection(b)
    return float(len(c))/(len(a)+len(b)-len(c))

# ....Here i want to write the loop to compute the jaccard of sentences as explained in the question

我想根据Jaccard Coeff评分>;0.5,形成一组相似的句子

谢谢


Tags: theto函数列表lensentences句子单子
1条回答
网友
1楼 · 发布于 2024-10-05 14:22:15

可以这样使用itertools.combination

import itertools

def do_some_stuff(first, second):
    print('comapring', first, 'to', second)

sentences_list = ['fisrt', 'second', 'third', 'forth']
combinations = itertools.combinations(sentences_list, 2)
for first, second in combinations:
    do_some_stuff(first, second)

上面的代码片段将为您提供以下输出:

comapring fisrt to second
comapring fisrt to third
comapring fisrt to forth
comapring second to third
comapring second to forth
comapring third to forth

相关问题 更多 >