我有一个字符串列表:
['twas', 'brillig', 'and', 'the', 'slithy', 'toves', 'did', 'gyre', 'and', 'gimble', 'in', 'the', 'wabe', 'all', 'mimsy', 'were', 'the', 'borogoves', 'and', 'the', 'mome', 'raths', 'outgrabe', '"beware', 'the', 'jabberwock', 'my', 'son', 'the', 'jaws', 'that', 'bite', 'the', 'claws', 'that', 'catch', 'beware', 'the', 'jubjub', 'bird', 'and', 'shun', 'the', 'frumious', 'bandersnatch', 'he', 'took', 'his', 'vorpal', 'sword', 'in', 'hand', 'long', 'time', 'the', 'manxome', 'foe', 'he', 'sought', 'so', 'rested', 'he', 'by', 'the', 'tumtum', 'tree', 'and', 'stood', 'awhile', 'in', 'thought', 'and', 'as', 'in', 'uffish', 'thought', 'he', 'stood', 'the', 'jabberwock', 'with', 'eyes', 'of', 'flame', 'came', 'whiffling', 'through', 'the', 'tulgey', 'wood', 'and', 'burbled', 'as', 'it', 'came', 'one', 'two', 'one', 'two', 'and', 'through', 'and', 'through', 'the', 'vorpal', 'blade', 'went', 'snicker-snack', 'he', 'left', 'it', 'dead', 'and', 'with', 'its', 'head', 'he', 'went', 'galumphing', 'back', '"and', 'has', 'thou', 'slain', 'the', 'jabberwock', 'come', 'to', 'my', 'arms', 'my', 'beamish', 'boy', 'o', 'frabjous', 'day', 'callooh', 'callay', 'he', 'chortled', 'in', 'his', 'joy', '`twas', 'brillig', 'and', 'the', 'slithy', 'toves', 'did', 'gyre', 'and', 'gimble', 'in', 'the', 'wabe', 'all', 'mimsy', 'were', 'the', 'borogoves', 'and', 'the', 'mome', 'raths', 'outgrabe']
如何返回与字符串中其他单词最不同的单词列表 - 基于与列表中所有其他单词的最小相似度和平均相似度值(作为浮点数)。
我绝对不知道该怎么做。我想我需要使用 cossim(word1,word2) 函数来计算“word1”和“word2”之间的相似度,因为我们的讲师给了我们这个函数,但我不知道如何使用它。
def cossim(word1,word2):
"""Calculate the cosine similarity between the two words"""
# sub-function for constructing a letter vector from argument `word`
# which returns the tuple `(vec,veclen)`, where `vec` is a dictionary of
# characters in `word`, and `veclen` is the length of the vector
def wordvec(word):
vec = defaultdict(int) # letter vector
# count the letters in the word
for char in word:
vec[char] += 1
# calculate the length of the letter vector
len = 0.0
for char in vec:
len += vec[char]**2
# return the letter vector and vector length
return vec,math.sqrt(len)
# calculate a vector,length tuple for each of `word1` and `word2`
vec1,len1 = wordvec(word1)
vec2,len2 = wordvec(word2)
# calculate the dot product between the letter vectors for the two words
dotprod = 0.0
for char in vec1:
dotprod += vec1[char]*vec2[char]
# divide by the lengths of the two vectors
if dotprod:
dotprod /= len1*len2
return dotprod
我应该从上面的列表中得到的答案应该是:
({'my'], 0.088487238234566931)
任何帮助是极大的赞赏,
谢谢,
基利