def cal_similarity(x, y): dict_x = dict(x) dict_y = dict(y)
时间: 2024-04-30 17:20:20 浏览: 102
这段代码定义了一个计算两个字典的相似度的函数。首先,函数将输入的两个字典转换为字典类型,并赋值给变量`dict_x`和`dict_y`。接下来,可以使用字典的`keys()`方法获取字典中所有的键值对,并使用`set()`函数将其转换为集合类型。然后,可以使用集合的交集和并集操作来计算两个字典的相似度。代码实现如下:
```
def cal_similarity(x, y):
dict_x = dict(x)
dict_y = dict(y)
set_x = set(dict_x.keys())
set_y = set(dict_y.keys())
intersection = set_x.intersection(set_y)
union = set_x.union(set_y)
similarity = len(intersection) / len(union)
return similarity
```
相关问题
import pandas as pd import math import jieba # 定义函数计算余弦相似度 def compute_xsd(ss1,ss2): stopwords = [] s1_cut = [i for i in jieba.cut(ss1, cut_all=True) if (i not in stopwords) and i != ' '] s2_cut = [i for i in jieba.cut(ss2, cut_all=True) if (i not in stopwords) and i != ' '] word_set = set(s1_cut).union(set(s2_cut)) word_dict = dict() i = 0 for word in word_set: word_dict[word] = i i += 1 s1_cut_code = [0] * len(word_dict) for word in s1_cut: s1_cut_code[word_dict[word]] += 1 s2_cut_code = [0] * len(word_dict) for word in s2_cut: s2_cut_code[word_dict[word]] += 1 sum = 0 sq1 = 0 sq2 = 0 for i in range(len(s1_cut_code)): sum += s1_cut_code[i] * s2_cut_code[i] sq1 += pow(s1_cut_code[i], 2) sq2 += pow(s2_cut_code[i], 2) try: result = round(float(sum) / (math.sqrt(sq1) * math.sqrt(sq2)), 3) except ZeroDivisionError: result = 0.0 return result # 定义两篇文章 text1 = '我喜欢打篮球' text2 = '篮球是我的爱好' # 定义空的DataFrame df_sim = pd.DataFrame(columns=['text1', 'text2', 'similarity']) # 计算两篇文章的相似度并存储到DataFrame中 for i in range(len(text1)): for j in range(len(text2)): sim = compute_xsd(text1[i], text2[j]) df_sim.loc[len(df_sim)] = [text1[i], text2[j], sim] # 输出DataFrame print(df_sim)以上代码,怎么计算出三个两篇文章三个相似度
这段代码是计算两篇文章的相似度,并将结果存储在一个DataFrame中。由于这里只有两篇文章,因此在循环中只需要进行一次计算,即计算text1和text2两个字符串的相似度。代码中的df_sim.loc[len(df_sim)] = [text1[i], text2[j], sim]是将计算结果存储在DataFrame中,其中text1[i]和text2[j]分别表示两篇文章,sim表示它们的相似度。由于只有一次计算,因此DataFrame中只有一行数据,其相似度就是存储在该行的'similarity'列中的值。你可以通过以下代码查看相似度的值:
```
print(df_sim['similarity'][0])
```
其中0表示第一行数据的索引,即唯一的一行数据。
import logging import jieba import gensim from gensim.models import Word2Vec def get_Segment(): texts = [] jieba.load_userdict("data\\name_dict.txt") with open('data\\in_the_name_of_people.txt','r',encoding='utf-8') as f: for line in f.readlines(): texts.append(list(jieba.cut(line.strip()))) with open('data\\in_the_name_of_people_segment.txt','w',encoding='utf-8')as f: for line in texts: f.write(" ".join(w for w in line)) f.write("\r\n") def getmodel(): logging.basicConfig(format='%(asctime)s : %(LeveLname)s : %(message)s',level=logging.INFO) sentences = word2vec.LineSentence('data\\in_the_name_of_people_segment.txt') model = word2vec.Word2Vec(sentences,min_count=1) return model if __name__=='__main__': get_Segment() model = getmodel() print('相似度: ',model.wv.similarity('人民','名义')) print(model.wv.similarity('候亮平','钟小艾')) print(model.mv.most_similar('候亮平',topn=10))
这段代码存在一些问题,我来帮你解释一下:
1. 代码中缺少了部分 import 语句,需要加上:
```
from gensim.models import word2vec
```
2. 在 `logging.basicConfig()` 函数的第一个参数中,`LeveLname` 应该是 `levelname`,需要修正。
3. 在 `getmodel()` 函数中,`word2vec.LineSentence()` 应该是 `word2vec.Text8Corpus()`,需要修正。
4. 在 `getmodel()` 函数中,`model.mv.most_similar()` 应该是 `model.wv.most_similar()`,需要修正。
修正后的代码如下:
```
import logging
import jieba
import gensim
from gensim.models import word2vec
def get_Segment():
texts = []
jieba.load_userdict("data\\name_dict.txt")
with open('data\\in_the_name_of_people.txt','r',encoding='utf-8') as f:
for line in f.readlines():
texts.append(list(jieba.cut(line.strip())))
with open('data\\in_the_name_of_people_segment.txt','w',encoding='utf-8')as f:
for line in texts:
f.write(" ".join(w for w in line))
f.write("\r\n")
def getmodel():
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.Text8Corpus('data\\in_the_name_of_people_segment.txt')
model = word2vec.Word2Vec(sentences, min_count=1)
return model
if __name__=='__main__':
get_Segment()
model = getmodel()
print('相似度: ',model.wv.similarity('人民','名义'))
print(model.wv.similarity('候亮平','钟小艾'))
print(model.wv.most_similar('候亮平',topn=10))
```
希望能帮到你!
阅读全文