如何在lis中比较两个列表并返回最大相似度

2024-09-30 01:21:59 发布

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

我有一张单子

list1 = ['good']

我有另一张“好”同义词的单子

^{pr2}$

现在我想列出最相似的词 有可能吗?在

假设单词good的相似度大于0.8,那么我想在列表中单独返回这些单词

在这里,让我考虑一下未损坏的有0.9左右的相似性

max_similar_list = ['unspoilt']

Tags: 列表相似性单词maxlist单子goodsimilar
2条回答

为此,您需要定义某种方法来查找一组单词之间的相似性。一种方法是生成单词嵌入的Word2Vec。 Gensim很好地实现了word2vec,请阅读以下内容:

https://radimrehurek.com/gensim/models/word2vec.html

对于word2Vec,您需要corpora来训练模型,然后为给定的单词集进行向量嵌入。然后使用任何距离函数(例如余弦)找到最接近它的单词

下面是一个示例代码:

#imports
from nltk.corpus import brown
import numpy as np
from gensim.models import Word2Vec

#Using brown corpus (category news) from nltk. Replace by your corpus with suitable words/sentences
sentences =brown.sents(categories = 'news')

#initialize and train model
model = Word2Vec(min_count=1)
model.build_vocab(sentences)
model.train(sentences, total_examples=model.corpus_count, epochs=model.iter)

# find similarity between two words
model.wv.similarity('good','well')

0.99978923463065106

注:这里,我比较两个词,你也可以用其他方法,从语料库中找出最相似的词。注意语料库中没有的单词。在

在这里我使用概率的概念,那些单词在列表中出现概率较高的单词是列表中相似度最高的单词。在

试试这个代码!我还附上了输出的截图。在

from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

list1 = ['good']
list2 = ['unspoilt', 'respectable', 'honorable', 'undecomposed', 'goodness', 'well', 'near', 'commodity', 'safe', 'dear', 'just', 'secure', 'in_force', 'practiced', 'trade_good', 'proficient', 'expert', 'good', 'sound', 'soundly', 'effective', 'in_effect', 'beneficial', 'dependable', 'unspoiled', 'estimable', 'salutary', 'adept', 'full', 'ripe','upright', 'skilful', 'right', 'serious', 'skillful', 'thoroughly','honest']
max_similar_list =[]
max=similar(list1[0],list2[1])
max_similar_list=list2[0]
for i in range(1,len(list2)):
  if (max < similar(list1[0],list2[i]) ):
    max=similar(list1[0],list2[i])
    max_similar_list=list2[i]
print("The highest similarity of words in list is '" , max_similar_list , "' with the probabilty of " , max)

enter image description here

相关问题 更多 >

    热门问题