import math def duibixiangliang(list1,list2): list=[] for i in range(len(list1)): list.append(list1[i]) for j in range(len(list2)): if list2[j] not in list: list.append(list2[j]) print("标准向量为:",list) return list def xlh(list,list0): listx=[] for i in range(len(list)): if list[i] in list0: listx.extend([1]) else: listx.extend([0]) return listx def cos(list1,list2): k=0 k1=0 k2=0 for i in range(len(list1)): k=k+list1[i]*list2[i] k1=k1+math.pow(list1[i],2) for i in range(len(list2)): k2=k2+math.pow(list2[i],2) p=k/(math.sqrt(k1)*math.sqrt(k2)) return p list1=['北京','你好','发展','繁荣','富强'] list2=['北京','腾飞','发展','迅速'] list=duibixiangliang(list1,list2) list1xlh=xlh(list,list1) list2xlh=xlh(list,list2) print("向量一:",list1xlh) print("向量二:",list2xlh) p=cos(list1xlh,list2xlh) print("向量的相似度为:",p)
12-16
1934
12-24