如何比较两个列表并返回列表中单词的最高相似度

时间:2018-03-01 04:00:11

标签: python similarity

我有一个清单

list1 = ['good']

我有另一个列表,其中包含单词" 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']

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

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

这里让我考虑未受破坏的相似性约为0.9

max_similar_list = ['unspoilt']

2 个答案:

答案 0 :(得分:0)

这里我使用的是概率概念。列表中单词概率较高的单词是列表中最高的相似单词。

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

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

答案 1 :(得分:0)

为此,您需要定义一些方法来查找一组单词之间的相似性。一种方法是使用Word2Vec生成单词嵌入。 Gensim有一个很好的word2vec实现,在这里阅读更多:

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

对于word2Vec,您需要语料库来训练模型,然后为给定的单词集进行矢量嵌入。然后使用任何距离函数(例如余弦)

找到最接近它的单词

以下是示例代码:

#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

P.S。 :在这里,我正在比较两个单词,你也可以使用其他方法,从语料库中给你最相似的单词。小心不在语料库中的单词。