文字列のリストがあります:
['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']
文字列内の他の単語と最も異なる単語のリストを返すにはどうすればよいですか - リスト内の他のすべての単語との最小類似度と平均類似度値 (float として) に基づいて。
これを行う方法がまったくわかりません。「word1」と「word2」の類似度を計算する cossim(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)
どんな助けでも大歓迎です、
ありがとう、
キーリー